import React from 'react';

import { useFind } from 'react-pouchdb';

import { lat2tile, lon2tile } from '../../lib/geo';
import { zoom0 } from '../../store/map';

const Gpx: React.FC<{ gpx: any }> = (props) => {
  console.log('gpx');

  var gpxes: any[] = [];

  gpxes = useFind({
    selector: {
      type: 'trkpt',
      gpx: props.gpx._id,
    },
    //   sort: ['trkpt.time'],
    //   use_index: 'type-trkpt-gpx-time3',
  });

  gpxes.sort((first: any, second: any) =>
    first.trkpt.time.localeCompare(second.trkpt.time)
  );

  const d = gpxes.reduce((previous: string, current: any, index: number) => {
    const action = index === 0 ? 'M' : index === 1 ? 'L' : '';
    const trkpt = current.trkpt;
    return `${previous} ${action} ${lon2tile(trkpt.$.lon, zoom0)}, ${lat2tile(
      trkpt.$.lat,
      zoom0
    )}`;
  }, '');

  return <path d={d} className='track' />;
};

export default Gpx;
