import react from 'react';

import { Point, MapScope } from './types';
import LayerStack from './LayerStack';
import { tileProviders } from './tile-providers';
import { lon2tile, lat2tile } from '../../lib/geo';

export interface MapProperties {
  scope: MapScope;
  numberOfTiledLayers?: number;
}

/**
 *
 * @returns A `<Map>` component
 *
 */
export const Map: react.FC<MapProperties> = (props: MapProperties) => {
  const tileProvider = tileProviders[props.scope.tileProvider];

  const tilesZoom = Math.min(
    Math.max(Math.round(props.scope.zoom), tileProvider.minZoom),
    tileProvider.maxZoom
  );
  const tilesCenter: Point = {
    x: lon2tile(props.scope.center.lon, tilesZoom),
    y: lat2tile(props.scope.center.lat, tilesZoom),
  };
  const softZoom = props.scope.zoom - tilesZoom;
  const relativeScale = 2 ** softZoom;
  const visibleTileSize = tileProvider.tileSize * relativeScale;
  const nbTilesLeft = window.innerWidth / 2 / visibleTileSize;
  const nbTilesTop = window.innerHeight / 2 / visibleTileSize;
  const firstTileLeft = Math.floor(tilesCenter.x - nbTilesLeft);
  const firstTileTop = Math.floor(tilesCenter.y - nbTilesTop);

  return (
    <>
      <LayerStack
        numberOfTiledLayers={props.numberOfTiledLayers}
        keyObject={{
          provider: props.scope.tileProvider,
          zoomLevel: tilesZoom,
          x: firstTileLeft,
          y: firstTileTop,
        }}
        coordinateSystem={{
          shift: {
            x: -((tilesCenter.x - nbTilesLeft) % 1) * visibleTileSize,
            y: -((tilesCenter.y - nbTilesTop) % 1) * visibleTileSize,
          },
          zoom: relativeScale,
        }}
      />
    </>
  );
};

export default Map;
