import react from 'react';
import TiledLayer from './TiledLayer';

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

interface TiledLayerConductorProperties {
  height: number;
  width: number;
  shift: Point;
  zoom: number;
  tileSize: number;
  numberOfZoomLevels?: number;
}

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

  const numberOfZoomLevels =
    props.numberOfZoomLevels === undefined
      ? 1
      : props.numberOfZoomLevels % 2 === 0
      ? props.numberOfZoomLevels + 1
      : props.numberOfZoomLevels;

  const layers = [];

  for (let i = 0; i < numberOfZoomLevels; i++) {
    layers.push(
      <TiledLayer
        key={`layer${i}`}
        height={props.height * 2 ** i}
        width={props.width * 2 ** i}
        shift={{ x: props.shift.x * 2 ** i, y: props.shift.y * 2 ** i }}
        zoom={props.zoom}
        layerZoom={2 ** -i}
        tileSize={256}
        nbTiles={nbTiles * 2 ** i}
        active={
          numberOfZoomLevels === 1
            ? true
            : i === 0
            ? props.zoom < 2 ** 0.5
            : i === numberOfZoomLevels - 1
            ? props.zoom >= 2 ** (i - 0.5)
            : props.zoom < 2 ** (i + 0.5) && props.zoom >= 2 ** (i - 0.5)
        }
      />
    );
  }

  return <>{layers}</>;
};

export default TiledLayerConductor;
