<!--
Leaflet map

@see https://leafletjs.com/
-->

<template>
  <div id="map-wrap">
    <client-only>
      <l-map :zoom="zoom" :center="center">
        <l-tile-layer :url="layerUrl" />
        <l-marker
          :lat-lng="latLong"
          draggable
          @update:latLng="onMoveMarker"
        />
      </l-map>

      <v-btn class="mr-4 mt-2 mb-2 ot_green ot_white--text" @click="updateMap">
        {{ $t('updateMap') }}
      </v-btn>
    </client-only>
  </div>
</template>

<script lang="ts">
import {computed, ComputedRef, defineComponent, ref, Ref, toRefs, ToRefs, useContext} from '@nuxtjs/composition-api'
import {QUERY_TYPE, TYPE_ALERT} from '~/types/enums'
import {AddressPostal} from '~/models/Core/AddressPostal'
import {AnyJson} from '~/types/interfaces'
import Page from "~/services/store/page";

export default defineComponent({
  props: {
    address: {
      type: Object as () => AddressPostal,
      required: true
    },
    zoom: {
      type: Number,
      required: true
    }
  },
  setup (props, { emit }) {
    const { $dataProvider, store, app: {i18n} } = useContext()
    const { address }: ToRefs = toRefs(props)
    const latitude: Ref<number> = ref(address.value.latitude ?? 0.0)
    const longitude: Ref<number> = ref(address.value.longitude ?? 0.0)

    const center: ComputedRef<Array<number>> = computed(() => [latitude.value, longitude.value])
    const latLong: ComputedRef<Array<number>> = computed(() => [latitude.value, longitude.value])

    const layerUrl: string = 'https://{s}.tile.osm.org/{z}/{x}/{y}.png'

    const updateMap = async () => {
      const response = await $dataProvider.invoke({
        type: QUERY_TYPE.DEFAULT,
        url: `/api/gps-coordinate-searching?street=${address.value.streetAddress}&cp=${address.value.postalCode}&city=${address.value.addressCity}`
      })
      const data = response.data
      if (data.length > 0) {
        latitude.value = data[0].latitude
        longitude.value = data[0].longitude

        address.value.latitude = data[0].latitude
        address.value.longitude = data[0].longitude
        emit('updateAddress', address.value)
      } else {
        new Page(store).addAlerts(TYPE_ALERT.ALERT, [i18n.t('no_coordinate_corresponding') as string])
      }
    }

    const onMoveMarker = async (event: AnyJson) => {
      if(event){
        address.value.latitude = event.lat
        address.value.longitude = event.lng
        emit('updateAddress', address.value)
      }
    }

    return {
      updateMap,
      center,
      latLong,
      layerUrl,
      onMoveMarker
    }
  }
})

</script>

<style scoped>
  #map-wrap{
    height: 30vh;
  }
</style>
