import React from 'react';

import { PigeonProps, Point } from 'pigeon-maps';
import GPX from 'gpx-parser-builder';
import { round } from 'lodash';

const GPXFigure: React.FC<PigeonProps> = (props: PigeonProps) => {
  const gpx = GPX.parse(localStorage.getItem('gpx'));

  const dirtyLatLngToPixel = (point: Point) => {
    if (props.mapState === undefined) {
      return undefined;
    }
    const latRange = props.mapState.bounds.ne[0] - props.mapState.bounds.sw[0];
    const lonRange = props.mapState.bounds.ne[1] - props.mapState.bounds.sw[1];
    const x = round(
      ((point[0] - props.mapState.bounds.sw[0]) * props.mapState.width) /
        lonRange
    );
    const y = round(
      ((point[1] - props.mapState.bounds.sw[1]) * props.mapState.height) /
        latRange
    );
    return [x, props.mapState.height - y];
  };

  const trkToPolyline = (gpxData: any) => {
    const latLongs: string[] = gpxData.trk[0].trkseg[0].trkpt.map(
      (trkpt: any) => {
        if (props.latLngToPixel === undefined) {
          return '';
        }
        const point: Point = [trkpt.$.lat, trkpt.$.lon];
        const pixelPoint = dirtyLatLngToPixel(point);
        if (pixelPoint === undefined) {
          return '';
        }
        return pixelPoint.join(' ');
      }
    );
    console.log('latLongs: ' + latLongs);
    return latLongs.join(' ');
  };

  return (
    <polyline
      points={trkToPolyline(gpx)}
      stroke='black'
      strokeWidth='3'
      fill='none'
    ></polyline>
  );
};

export default GPXFigure;
