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

import {useAsset} from '@/context/assets.js';

const TileLayerInternal = PixiComponent('TileLayer', {
  create: () => {
    const container = new Container();
    container.addChild(new CompositeTilemap());
    return container;
  },
  applyProps: (container, {mask: oldMask, tileLayer: oldTileLayer}, props) => {
    const {asset, mask, tileLayer} = props;
    const extless = tileLayer.source.slice('/assets/'.length, -'.json'.length);
    const {textures} = asset;
    if (tileLayer === oldTileLayer) {
      return;
    }
    if (oldMask) {
      container.removeChildAt(1);
      container.mask = undefined;
    }
    if (mask) {
      container.addChild(mask);
      container.mask = mask;
    }
    const tilemap = container.children[0];
    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 {mask, tileLayer} = props;
  const asset = useAsset(tileLayer.source);
  if (!asset) {
    return false;
  }
  return (
    <>
      <TileLayerInternal
        {...props}
        asset={asset}
        mask={mask}
      />
    </>
  );
}
