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

export const Wpt: Component<Props> = ({ vectorSource, wptId: wptId }) => {
  const [wpt] = createResource(
    wptId,
    async () =>
      await dispatch({
        action: 'getWpt',
        params: {
          id: wptId,
        },
      })
  );

  createEffect(() => {
    console.log({ caller: 'Wpt', vectorSource, wptId, wpt: wpt() });

    if (wpt()) {
      let geo: any = {
        type: 'FeatureCollection',
        features: [
          {
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: [wpt().$.lon, wpt().$.lat],
            },
            properties: { type: 'wpt', ...wpt(), id: wptId },
          },
        ],
      };

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

  return <></>;
};

export default Wpt;
