import { Overlay, MapState, Point } from 'pigeon-maps';
import React from 'react';

const GPXOverlay: React.FC<{
  mapState: any;
  latLngToPixel: any;
  track: any;
}> = (props: {
  mapState: MapState;
  latLngToPixel:
    | ((
        latLng: Point,
        center?: Point | undefined,
        zoom?: number | undefined
      ) => Point)
    | undefined;
  track: any;
}) => {
  const trkToPolyline = (trk: any) => {
    const latLongs: string[] = trk.trkseg[0].trkpt.map((trkpt: any) => {
      if (props.latLngToPixel === undefined) {
        return '';
      }
      const point: Point = [trkpt['$'].lat, trkpt['$'].lon];
      const pixelPoint = props.latLngToPixel(point);
      if (pixelPoint === undefined) {
        return '';
      }
      return pixelPoint.join(' ');
    });
    console.log('latLongs: ' + latLongs);
    return latLongs.join(' ');
  };

  return (
    <Overlay mapState={props.mapState} latLngToPixel={props.latLngToPixel}>
      {props.mapState.width > 0 && (
        <svg
          xmlns='http://www.w3.org/2000/svg'
          viewBox={'0 0 ' + props.mapState.width + ' ' + props.mapState.height}
          width={props.mapState.width}
          height={props.mapState.height}
          >
          <polyline
            points={trkToPolyline(props.track)}
            stroke="black" strokeWidth="3" fill="none"
          ></polyline>
        </svg>
      )}
    </Overlay>
  );
};

export default GPXOverlay;
