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

import {Assets} from '@pixi/assets';

const TileLayerInternal = PixiComponent('TileLayer', {
  create: () => new CompositeTilemap(),
  applyProps: (tilemap, {tiles: oldTiles}, props) => {
    const {asset, tiles, tileSize, size, x, y} = props;
    const {textures} = asset;
    tilemap.position.x = x;
    tilemap.position.y = y;
    if (tiles === oldTiles) {
      return;
    }
    tilemap.clear();
    let i = 0;
    for (let y = 0; y < size.y; ++y) {
      for (let x = 0; x < size.x; ++x) {
        tilemap.tile(textures[tiles[i++]], tileSize.x * x, tileSize.y * y);
      }
    }
  },
})

export default function TileLayer(props) {
  const {tileset} = props;
  const [asset, setAsset] = useState();
  useEffect(() => {
    const asset = Assets.get(tileset);
    if (asset) {
      setAsset(asset);
    }
    else {
      Assets.load(tileset).then(setAsset);
    }
  }, [setAsset, tileset]);
  if (!asset) {
    return false;
  }
  return (
    <TileLayerInternal
      {...props}
      asset={asset}
    />
  );
}
