import { Component, createEffect, createResource } from 'solid-js';

import dispatch from '../../workers/dispatcher-main';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import { Feature } from 'ol';

interface Props {
  trksegId: string;
  vectorSource: VectorSource;
}

export const Trkseg: Component<Props> = ({ vectorSource, trksegId }) => {
  const [trkseg] = createResource(
    trksegId,
    async () =>
      await dispatch({
        action: 'getTrkseg',
        params: {
          id: trksegId,
        },
      })
  );

  createEffect(() => {
    console.log({ caller: 'Trkseg', vectorSource, trksegId, trkseg: trkseg() });

    if (trkseg()) {
      let geo: any = {
        type: 'FeatureCollection',
        features: [
          {
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: [trkseg().trkpt[0].$.lon, trkseg().trkpt[0].$.lat],
            },
            properties: { type: 'trkseg-start', id: trksegId },
          },
          {
            type: 'Feature',
            geometry: {
              type: 'LineString',
              coordinates: trkseg().trkpt.map((trkpt: any) => [
                trkpt.$.lon,
                trkpt.$.lat,
              ]),
            },
            properties: { type: 'trkseg', id: trksegId },
          },
          {
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: [
                trkseg().trkpt.at(-1).$.lon,
                trkseg().trkpt.at(-1).$.lat,
              ],
            },
            properties: { type: 'trkseg-finish', id: trksegId },
          },
        ],
      };

      const features = new GeoJSON().readFeatures(geo);
      console.log({ caller: 'Trkseg', features });
      vectorSource.addFeatures(features);
    }
  });

  return <></>;
};

export default Trkseg;
