<template>
  <div id="address_map" />
</template>

<script>
import L from "leaflet";
import markerIconPng from "leaflet/dist/images/marker-icon.png";
import "leaflet/dist/leaflet.css";

const lonLatForLeaflet = (coordinates) => {
  return [coordinates[1], coordinates[0]];
};

export default {
  name: "AddressMap",
  props: ["entity"],
  data() {
    return {
      map: null,
      marker: null,
    };
  },
  computed: {
    center() {
      return this.entity.addressMap.center;
    },
    hasAddressPoint() {
      if (Object.keys(this.entity.address).length === 0) {
        return false;
      }
      if (null !== this.entity.address.addressReference) {
        return true;
      }
      if (
        null !== this.entity.address.postcode &&
        null !== this.entity.address.postcode.center
      ) {
        return true;
      }
      return false;
    },
    /**
     *
     * @returns {coordinates: [float, float], type: "Point"}
     */
    addressPoint() {
      if (Object.keys(this.entity.address).length === 0) {
        return null;
      }

      if (null !== this.entity.address.addressReference) {
        return this.entity.address.addressReference.point;
      }

      if (
        null !== this.entity.address.postcode &&
        null !== this.entity.address.postcode.center
      ) {
        return this.entity.address.postcode.center;
      }

      return null;
    },
  },
  methods: {
    init() {
      this.map = L.map("address_map");

      if (!this.hasAddressPoint) {
        this.map.setView(
          lonLatForLeaflet(this.entity.addressMap.center),
          this.entity.addressMap.zoom,
        );
      } else {
        this.map.setView(lonLatForLeaflet(this.addressPoint.coordinates), 15);
      }

      this.map.scrollWheelZoom.disable();

      L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        attribution:
          '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
      }).addTo(this.map);

      const markerIcon = L.icon({
        iconUrl: markerIconPng,
        iconAnchor: [12, 41],
      });

      if (!this.hasAddressPoint) {
        this.marker = L.marker(
          lonLatForLeaflet(this.entity.addressMap.center),
          { icon: markerIcon },
        );
      } else {
        this.marker = L.marker(
          lonLatForLeaflet(this.addressPoint.coordinates),
          { icon: markerIcon },
        );
      }
      this.marker.addTo(this.map);
    },
    update() {
      if (this.marker && this.entity.addressMap.center) {
        this.marker.setLatLng(lonLatForLeaflet(this.entity.addressMap.center));
        this.map.panTo(lonLatForLeaflet(this.entity.addressMap.center));
      }
    },
  },
  mounted() {
    this.init();
  },
};
</script>
