import react, { useEffect, useState } from 'react';
import Tile from './Tile';
import fakeTile from './FakeTile.svg';

interface Point {
  x: number;
  y: number;
}

interface TiledLayerProperties {
  height: number;
  width: number;
  shift: Point;
  zoom: number;
}

const TiledLayer: react.FC<TiledLayerProperties> = (
  props: TiledLayerProperties
) => {
  const nbTiles =
    Math.ceil((Math.max(props.width, props.height) * 2) / 256) + 2;

  var initialTiledLayer: any[][] = [];
  for (let row = 0; row < nbTiles; row++) {
    let tileRow = [];
    for (let col = 0; col < nbTiles; col++) {
      tileRow.push(<g key={`${row}/${col}`} />);
    }
    initialTiledLayer.push(tileRow);
  }

  const [tiledLayer, setTiledLayer] = useState(initialTiledLayer);

  useEffect(() => {
    const firstVisibleTiles = {
      x: Math.max(Math.floor(-props.shift.x / 256 / props.zoom), 0),
      y: Math.max(Math.floor(-props.shift.y / 256 / props.zoom), 0),
    };

    const lastVisibleTiles = {
      x: Math.min(
        Math.ceil(firstVisibleTiles.x + props.width / 256 / props.zoom),
        nbTiles - 1
      ),
      y: Math.min(
        Math.ceil(firstVisibleTiles.y + props.height / 256 / props.zoom),
        nbTiles - 1
      ),
    };
    console.log(
      `Adding new tiles if needed for  ${JSON.stringify(
        firstVisibleTiles
      )}/${JSON.stringify(lastVisibleTiles)}.`
    );
    const newTiledLayer: any[][] = [];
    for (let row = 0; row < nbTiles; row++) {
      let tileRow = [];
      for (let col = 0; col < nbTiles; col++) {
        const key = `${row}/${col}`;
        if (
          tiledLayer[row][col].type === 'g' &&
          row >= firstVisibleTiles.y &&
          row <= lastVisibleTiles.y &&
          col >= firstVisibleTiles.x &&
          col <= lastVisibleTiles.x
        ) {
          console.log(`Adding tile ${row}/${col}`);
          tileRow.push(
            <Tile
              key={key}
              href={fakeTile}
              x={col * 256}
              y={row * 256}
              delay={1000}
            />
          );
        } else {
          tileRow.push(tiledLayer[row][col]);
        }
      }
      newTiledLayer.push(tileRow);
    }

    setTiledLayer(newTiledLayer);
  }, [props.shift, props.zoom, nbTiles, props.height, props.width]);

  return <>{tiledLayer}</>;
};

export default TiledLayer;
