import {PixiComponent} from '@pixi/react';
import '@pixi/spritesheet'; // NECESSARY!
import {CompositeTilemap} from '@pixi/tilemap';

import useAsset from '@/hooks/use-asset.js';

const TileLayerInternal = PixiComponent('TileLayer', {
  create: () => new CompositeTilemap(),
  applyProps: (tilemap, {tileLayer: oldTileLayer}, props) => {
    const {asset, tileLayer} = props;
    const extless = tileLayer.source.slice('/assets/'.length, -'.json'.length);
    const {textures} = asset;
    if (tileLayer === oldTileLayer) {
      return;
    }
    tilemap.clear();
    let i = 0;
    for (let y = 0; y < tileLayer.area.y; ++y) {
      for (let x = 0; x < tileLayer.area.x; ++x) {
        tilemap.tile(textures[`${extless}/${tileLayer.data[i++]}`], tileLayer.tileSize.x * x, tileLayer.tileSize.y * y);
      }
    }
  },
})

export default function TileLayer(props) {
  const {tileLayer} = props;
  const asset = useAsset(tileLayer.source);
  if (!asset) {
    return false;
  }
  return (
    <TileLayerInternal
      {...props}
      asset={asset}
    />
  );
}
