<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import type { 
  GalleryEntry,
  GalleryList,
  GalleryListDefinition,
  RoutedWindow,
} from '@goldenwere/mackenzii-types'

import { amendVariantsWithDefaults, getTitleFromEntryOrId } from './gallery-utilities'
import { fetchAndParseYaml } from 'src/utilities/fetch'
import { getCurrentRoute } from 'src/utilities/vuetils'
import { useRouteStore } from 'src/routes'

import EmbedableContent from 'src/components/shared/embedable-content.vue'

declare const window: RoutedWindow

const props = defineProps<{
  variants: string[]
}>()

const emits = defineEmits<{
  (e: 'loaded'): void
}>()

const ready = ref(false)
const config = ref(null! as GalleryList)
const entry = ref(null! as GalleryEntry)
const id = ref('')
const currentRoute = getCurrentRoute()
const routeStore = useRouteStore()
const routeConfig = routeStore._routes[currentRoute.path.substring(0, currentRoute.path.length - 5)] as GalleryListDefinition
const routeSubConfig = routeStore._routes[currentRoute.path]
const title = ref('')
const styles = computed(() => {
  const stylesReturn: Record<string, string> = {}
  if (!!entry.value.background) {
    stylesReturn.background = entry.value.background
  }
  return stylesReturn
})

onMounted(async () => {
  config.value = await fetchAndParseYaml<GalleryList>(routeConfig.config)
  let currentEntries = config.value.entries
  for (let i = 0; i < props.variants.length - 1; ++i) {
    currentEntries = amendVariantsWithDefaults(currentEntries[props.variants[i]])!
  }
  entry.value = currentEntries[props.variants[props.variants.length - 1]]
  id.value = props.variants[props.variants.length - 1]
  title.value = getTitleFromEntryOrId(entry.value, id.value)
  document.title = routeSubConfig.fullTitle?.replace('$ENTRY', title.value)
  routeStore.setBreadcrumbs(currentRoute, title.value)
  window.routeConfig = {...routeConfig}
  window.routeSubConfig = {...routeSubConfig}
  window.routeContentConfig = {...entry.value}

  ready.value = true
  emits('loaded')
})
</script>

<template lang="pug">
.template.gallery-view
  Transition
    .view-wrapper(
      v-if='ready'
    )
      .view-outlet
        img(
          :src='entry.url || entry.thumbnailUrl'
          :style='styles'
        )
      .view-content
        p {{ title }}
        dl.info
          .info-entry(
            v-for='(field, key) in entry.fields'
            :class='key'
          )
            dt {{ key }}
            dd {{ field }}
        EmbedableContent(
          :content='entry.description'
        )
</template>

<style scoped lang="sass">

</style>
