import react, { ReactNode } from 'react';
import { lat2tile, lon2tile } from '../../lib/geo';
import { geoPoint, Rectangle, TileKeyObject } from './types';

export interface MarkerProperties {
  coordinates: geoPoint;
  icon: ReactNode;
  keyObject?: TileKeyObject;
  zoom?: number;
  viewPort?: Rectangle;
}

export const Marker: react.FC<MarkerProperties> = (props: MarkerProperties) => {
  console.log(`Rendering Marker`);

  if (
    props.keyObject === undefined ||
    props.zoom === undefined ||
    props.viewPort === undefined
  ) {
    console.log(`Marker props undefined: ${JSON.stringify(props)} `);
    return null;
  }

  const x = lon2tile(props.coordinates.lon, props.keyObject.zoomLevel);
  const y = lat2tile(props.coordinates.lat, props.keyObject.zoomLevel);
  if (
    x < props.viewPort.topLeft.x ||
    x > props.viewPort.bottomRight.x + 1 ||
    y < props.viewPort.topLeft.y ||
    y > props.viewPort.bottomRight.y + 1
  ) {
    console.log(
      `Marker ${x}, ${y} out of viewport: ${JSON.stringify(props.viewPort)} `
    );
    return null;
  }
  return (
    <g transform={`translate(${x}, ${y}) scale(${1 / props.zoom})`}>
      {props.icon}
    </g>
  );
};

export default Marker;
