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 {
  rteId: string;
  vectorSource: VectorSource;
}

export const Rte: Component<Props> = ({ vectorSource, rteId }) => {
  const [rte, setRte] = createSignal<Rte>();
  const [dispatchId, setDispatchId] = createSignal<number>(-1);

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

  dispatch(
    {
      action: 'getAndWatch',
      params: {
        id: rteId,
        method: 'getRte',
      },
    },
    rteCallBack,
    true
  );

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

  createEffect(() => {
    console.log({ caller: 'Rte', vectorSource, rteId, rte: rte() });

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

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

  return <></>;
};

export default Rte;
