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

import OlMap from 'ol/Map';

import dispatch, { cancelDispatch } from '../../workers/dispatcher-main';
import Trk from '../trk';
import getUri from '../../lib/ids';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';

import style from './styles';
import Wpt from '../wpt';
import Rte from '../rte';

interface Props {
  gpxId: string;
  map: () => OlMap | null;
}

export const Gpx: Component<Props> = ({ map, gpxId }) => {
  const [gpx, setGpx] = createSignal<Gpx>();
  const [dispatchId, setDispatchId] = createSignal<number>(-1);

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

  dispatch(
    {
      action: 'getAndWatch',
      params: {
        id: gpxId,
        method: 'getGpx',
      },
    },
    gpxCallBack,
    true
  );

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

  const vectorSource = new VectorSource();
  const vectorLayer = new VectorLayer({
    source: vectorSource,
    style,
    declutter: false,
  });
  createEffect(() => map()?.addLayer(vectorLayer));

  createEffect(() => {
    console.log({ caller: 'Gpx', map: map(), gpxId, gpx: gpx(), vectorLayer });
  });

  return (
    <>
      <For each={gpx() ? gpx().trk || [] : []}>
        {(trkId: string) => {
          console.log({ caller: 'Gpx / loop', trkId });
          return (
            <Suspense>
              <Trk vectorSource={vectorSource} trkId={trkId} />
            </Suspense>
          );
        }}
      </For>
      <For each={gpx() ? gpx().rte || [] : []}>
        {(rteId: string) => {
          console.log({ caller: 'Gpx / loop', rteId });
          return (
            <Suspense>
              <Rte vectorSource={vectorSource} rteId={rteId} />
            </Suspense>
          );
        }}
      </For>
      <For each={gpx() ? gpx().wpt || [] : []}>
        {(wptId: string) => {
          console.log({ caller: 'Gpx / loop', wptId });
          return (
            <Suspense>
              <Wpt vectorSource={vectorSource} wptId={wptId} />
            </Suspense>
          );
        }}
      </For>
    </>
  );
};

export default Gpx;
