<template>
  <div id="viewer" class="entry-viewer"></div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import type { ViewerInterface, MapInterface } from '@/views/interfaces/common'
import { getIgnTiles } from '@/utils/mapAndViewer'
import { Viewer, StandaloneMap } from 'geovisio'
import { createUrlLink } from '@/utils'
import { createLink } from '@/components-viewer/reportLink'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
let mapIsLoaded = ref<boolean>(false)
let viewer = ref()

const props = defineProps({
  fetchOptions: { type: Object, default: {} },
  geovisioViewer: { type: Boolean, default: true },
  bbox: { type: Array, default: null },
  userId: { type: String, default: '' }
})
defineExpose({
  viewer
})
onMounted(async () => {
  const tiles = import.meta.env.VITE_TILES
  const maxZoom = import.meta.env.VITE_MAX_ZOOM
  const zoom = import.meta.env.VITE_ZOOM
  const center = import.meta.env.VITE_CENTER
  let paramsViewer: ViewerInterface
  let paramsMap: MapInterface

  try {
    if (props.geovisioViewer) {
      paramsViewer = { map: { startWide: true } }
      if (center && center !== '') {
        const centerMap = center.split(',').map((el: string) => parseInt(el))
        paramsViewer = {
          map: {
            ...paramsViewer.map,
            center: centerMap
          }
        }
      }
      if (zoom && zoom !== '') {
        paramsViewer = {
          map: {
            ...paramsViewer.map,
            zoom: parseFloat(zoom)
          }
        }
      }
      if (maxZoom && maxZoom !== '') {
        paramsViewer = {
          map: {
            ...paramsViewer.map,
            maxZoom: parseInt(maxZoom)
          }
        }
      }
      if (tiles) {
        const style = tiles.includes('wxs.ign.fr') ? await getIgnTiles() : tiles
        paramsViewer = {
          map: {
            ...paramsViewer.map,
            style
          }
        }
      }
      if (props.fetchOptions) {
        paramsViewer = {
          ...paramsViewer,
          ...props.fetchOptions
        }
      }
      const reportLink = document.createElement('div')
      reportLink.className = 'gvs-group gvs-group-large gvs-group-btnpanel'
      viewer.value = new Viewer(
        'viewer', // Div ID
        `${import.meta.env.VITE_API_URL}/api/search`,
        {
          ...paramsViewer,
          widgets: { customWidget: reportLink }
        }
      )
      if (viewer.value && viewer.value.addEventListener) {
        viewer.value.addEventListener(
          'picture-loaded',
          async (e: { detail: { picId: string } }): Promise<void> => {
            const href = t('pages.home.report_mail', {
              picId: e.detail.picId,
              link: createUrlLink(e.detail.picId)
            })
            reportLink.innerHTML = createLink(
              href,
              t('pages.home.report_button_text')
            )
          }
        )
      }
    } else {
      paramsMap = { minZoom: 7 }
      if (tiles) {
        const style = tiles.includes('wxs.ign.fr') ? await getIgnTiles() : tiles
        paramsMap = {
          ...paramsMap,
          style
        }
      }
      const bbox = [props.bbox[0], props.bbox[1], props.bbox[2], props.bbox[3]]
      viewer.value = new StandaloneMap(
        'viewer', // Div ID
        `${import.meta.env.VITE_API_URL}/api/search`,
        {
          ...paramsMap,
          bounds: bbox,
          zoom: 14
        }
      )
      viewer.value.addEventListener('ready', () => {
        viewer.value.setFilters({ user: props.userId }, true)
        viewer.value.fitBounds(bbox, {
          padding: { top: 70, bottom: 70, left: 70, right: 70 },
          maxZoom: 14,
          speed: 10
        })
      })
    }
    mapIsLoaded.value = true
  } catch (err) {
    console.log(err)
  }
})
onUnmounted(() => {
  if (viewer.value && props.geovisioViewer) viewer.value.destroy()
})
</script>

<style scoped lang="scss">
.entry-viewer {
  font-size: initial;
  position: relative;
  width: 100%;
  height: 100%;
}
.gvs-focus-map .entry-report-button {
  display: none;
}
</style>
