import { Component, createSignal, onMount } from 'solid-js';
import { useParams, useNavigate } 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';

const Map: Component = () => {
  const [getMap, setMap] = createSignal<OlMap | null>(null);
  const params = useParams();
  const navigate = useNavigate();
  let target: HTMLDivElement;

  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 olMap = new OlMap({
      view: new View({
        center: [+params.lon, +params.lat],
        zoom: +params.zoom,
        rotation: +params.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;
