import { Component, createEffect, createSignal, onMount } from 'solid-js';
import {
  useParams,
  useNavigate,
  useRouteData,
  useBeforeLeave,
} from '@solidjs/router';
import OlMap from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import Attribution from 'ol/control/Attribution';
import Rotate from 'ol/control/Rotate';
import ScaleLine from 'ol/control/ScaleLine';
import Control from 'ol/control/Control';
import OSM from 'ol/source/OSM';
import { useGeographic as olUseGeographic } from 'ol/proj';

import 'ol/ol.css';
import './Map.css';
import { Collection } from 'ol';

const Map: Component = () => {
  const [getMap, setMap] = createSignal<OlMap | null>(null);
  const params = useParams();
  const [state, setState] = createSignal(params);
  createEffect(() => {
    setState(params);
    const map = getMap();
    const view = map?.getView();
    view?.animate({
      center: [+state().lon, +state().lat],
      rotation: +state().rotation,
      zoom: +state().zoom,
      duration: 1000,
    });
  });
  const navigate = useNavigate();
  let target: HTMLDivElement;
  console.log({ caller: 'Map', center: params.center });

  onMount(() => {
    olUseGeographic();

    const changeListener = (event: any) => {
      const map = getMap();
      const view = map?.getView();
      const center = view?.getCenter();
      if (center) {
        navigate(
          `/map/${center[0]}/${
            center[1]
          }/${view?.getZoom()}/${view?.getRotation()}`
        );
      }
      console.log({
        caller: 'Map / changeListener',
        event,
        params,
        map,
      });
    };

    const controls = new Collection([
      new Attribution({ collapsible: true }),
      new Rotate(),
      new ScaleLine({ bar: true }),
      //      new Control({ element: getLocation.current ?? undefined }),
    ]);
    const olMap = new OlMap({
      view: new View({
        center: [+state().lon, +state().lat],
        zoom: +state().zoom,
        rotation: +state().rotation,
      }),
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
        //new VectorLayer({ source: newSource }),
      ],
      target: target,
      controls,
    });
    olMap.on(['moveend'], changeListener);
    setMap(olMap);
  });

  // @ts-ignore
  return <div class='ol-map' ref={target} />;
};

export default Map;
