<script setup lang="ts">
import { ref, watch } from "vue";
import { loadModules } from "esri-loader";

const props = defineProps({
  modal: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  close: {
    type: Function,
  },
  data: {
    type: Object,
  },
});

const isLoadMap = ref<boolean>(false);
async function initializeMap(lat: number, long: number) {
  isLoadMap.value = false;
  try {
    // Load modules of ArcGIS
    const [esriConfig, Map, MapView, Point, Graphic] = await loadModules([
      "esri/config",
      "esri/Map",
      "esri/views/MapView",
      "esri/geometry/Point",
      "esri/Graphic",
    ]);
    // Set apiKey
    // esriConfig.apiKey = apiKey.value;
    const map = new Map({
      // basemap: "arcgis-topographic",
      basemap: "streets",
    });

    const point = new Point({
      type: "point",
      longitude: long,
      latitude: lat,
    });

    const mapView = new MapView({
      container: "mapViewDisplay",
      map: map,
      center: {
        latitude: lat,
        longitude: long,
      }, // Set the initial map center current position
      zoom: 18,
      ui: {
        components: [], // Empty array to remove all default UI components
      },
    });

    // Pin icon
    const pinSymbol = {
      type: "picture-marker",
      url: "http://maps.google.com/mapfiles/ms/icons/red.png",
      width: "32px",
      height: "32px",
    };

    // Create a graphic using the point and symbol
    const pointGraphic = new Graphic({
      geometry: point,
      symbol: pinSymbol,
    });
    mapView.graphics.add(pointGraphic);
    setTimeout(() => {
      isLoadMap.value = true;
    }, 1500);
  } catch (error) {
    console.error("Error loading the map", error);
  }
}

watch(
  () => props.modal,
  () => {
    const lat =
      props.title === "พิกัดสถานที่เข้างาน"
        ? props.data?.checkInLat
        : props.data?.checkOutLat;
    const long =
      props.title === "พิกัดสถานที่เข้างาน"
        ? props.data?.checkInLon
        : props.data?.checkOutLon;

    props.modal && initializeMap(lat, long);
  }
);
</script>
<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="width: 950px; max-width: 80vw; min-height: 65vh">
      <q-toolbar>
        <q-toolbar-title class="text-subtitle1 text-weight-bold">
          <span style="margin-right: 0"> {{ props.title }}</span>
        </q-toolbar-title>
        <q-btn
          for="closeDialog"
          icon="close"
          unelevated
          round
          dense
          @click="props.close?.()"
          style="color: #eb0505; background-color: #ffdede"
        />
      </q-toolbar>
      <q-separator />
      <q-card flat bordered>
        <div id="mapViewDisplay" style="height: 65vh" v-show="isLoadMap"></div>
        <q-skeleton height="65vh" square v-if="!isLoadMap" />
      </q-card> </q-card
  ></q-dialog>
</template>

<style scoped></style>
