<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { 
  BlogList,
  BlogEntry,
  BlogListDefinition,
  RoutedWindow,
} from '@goldenwere/mackenzii-types'

import { fetchAndParseMarkdown, fetchAndParseYaml, fetchConfigByIdFromList } 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 emits = defineEmits<{
  (e: 'loaded'): void
}>()

const ready = ref(false)
const info = ref(null! as BlogEntry)
const content = ref('')
const currentRoute = getCurrentRoute()
const routeStore = useRouteStore()
const routeConfig = routeStore._routes[currentRoute.path.substring(0, currentRoute.path.length - 5)] as BlogListDefinition
const routeSubConfig = routeStore._routes[currentRoute.path]

onMounted(async () => {
  const config = await fetchAndParseYaml<BlogList>(routeConfig.config)
  info.value = await fetchConfigByIdFromList(config, currentRoute.query.id as string)
  const md = await fetchAndParseMarkdown(info.value.url)
  content.value = md
  document.title = routeSubConfig.fullTitle?.replace('$ENTRY', info.value.title)
  routeStore.setBreadcrumbs(currentRoute, info.value.title)
  window.routeConfig = {...routeConfig}
  window.routeSubConfig = {...routeSubConfig}
  window.routeContentConfig = {...info.value}

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

<template lang="pug">
.template.blog-view
  Transition
    article(
      v-if='ready'
    )
      EmbedableContent(
        :content='content'
      )
</template>

<style lang="sass">

</style>
