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

import OlMap from 'ol/Map';

import dispatch from '../../workers/dispatcher-main';
import getUri from '../../lib/ids';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';

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: 'LineString',
              coordinates: trkseg().trkpt.map((trkpt: any) => [
                trkpt.$.lon,
                trkpt.$.lat,
              ]),
            },
          },
        ],
      };

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

  return <></>;
};

export default Trkseg;
