import { WorldLoader } from '../../common/world/world-loader';
import { join } from 'path';
import jimp from 'jimp';
import { ASSETS } from '../constants';
import { to1D } from '../../common/convert';

export class ServerWorldLoader implements WorldLoader {
  constructor(private _path = join(ASSETS, 'terrain', 'region')) {}

  async loadHeightMap(
    chunkX: number,
    chunkY: number,
    scale: number,
  ): Promise<number[]> {
    console.log(`<WORLD> Loading region ${chunkX}, ${chunkY}..`);
    const regionHeight = join(this._path, `height-${chunkX}-${chunkY}.png`);
    const image = await jimp.read(regionHeight);
    const width = image.getWidth();
    const height = image.getHeight();
    const heights = new Array(width * height);

    for (let x = 0; x < width; x++) {
      for (let y = 0; y < height; y++) {
        const id = to1D(x, y, width);
        const rgb = (image.getPixelColor(x, y) - 255) / 256;
        heights[id] = (((rgb >> 16) & 255) * scale) / 255;
      }
    }

    return heights;
  }
}
