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

import dispatch, { cancelDispatch } from '../../workers/dispatcher-main';
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, setTrkseg] = createSignal<Trkseg>();
  const [dispatchId, setDispatchId] = createSignal<number>(-1);

  const trksegCallBack = (error: any, result: any, id?: number) => {
    if (error) {
      console.error({ caller: 'trksegCallBack', error });
    } else {
      console.log({ caller: 'trksegCallBack', result });
      setTrkseg(result);
    }
    if (id) {
      setDispatchId(id);
    }
  };

  dispatch(
    {
      action: 'getAndWatch',
      params: {
        id: trksegId,
        method: 'getTrkseg',
      },
    },
    trksegCallBack,
    true
  );

  onCleanup(() => {
    dispatch({
      action: 'cancelWatch',
      params: {
        id: trksegId,
        method: 'getTrkseg',
      },
    });
    cancelDispatch(dispatchId());
  });

  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 },
            id: `${trksegId}/start`,
          },
          {
            type: 'Feature',
            geometry: {
              type: 'LineString',
              coordinates: trkseg().trkpt.map((trkpt: any) => [
                trkpt.$.lon,
                trkpt.$.lat,
              ]),
            },
            properties: { type: 'trkseg', id: trksegId },
            id: trksegId,
          },
          {
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: [
                trkseg().trkpt.at(-1).$.lon,
                trkseg().trkpt.at(-1).$.lat,
              ],
            },
            properties: { type: 'trkseg-finish', id: trksegId },
            id: `${trksegId}/end`,
          },
        ],
      };

      const features = new GeoJSON().readFeatures(geo);
      console.log({ caller: 'Trkseg', features });
      [`${trksegId}/start`, trksegId, `${trksegId}/end`].forEach((id) => {
        const feature = vectorSource.getFeatureById(id);
        if (feature) {
          vectorSource.removeFeature(feature);
        }
      });
      vectorSource.addFeatures(features);
    }
  });

  return <></>;
};

export default Trkseg;
