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

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

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

export const Wpt: Component<Props> = ({ vectorSource, wptId: wptId }) => {
  const [wpt, setWpt] = createSignal<Wpt>();

  const wptCallBack = (error: any, result: any) => {
    if (error) {
      console.error({ caller: 'wptCallBack', error });
    } else {
      console.log({ caller: 'wptCallBack', result });
      setWpt(result);
    }
  };

  dispatch(
    {
      action: 'getAndWatch',
      params: {
        id: wptId,
        method: 'getWpt',
      },
    },
    wptCallBack,
    true
  );

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

    if (wpt() && !tree[wptId]) {
      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);
      setBranch(wptId, { features, updateHandler });
    }
  });

  const updateHandler = (feature: Feature) => {
    console.log({
      caller: 'Wpt / updateHandler / clicked',
      feature,
    });
  };

  return <></>;
};

export default Wpt;
