<template>
  <div class="pptEditor">
    <Screen v-if="screening" />
    <Editor v-else />
  </div>
</template>

<script setup lang="ts">
import Editor from "../Editor/index.vue"
import Screen from "../Screen/index.vue"
import { onMounted } from "vue"
import { storeToRefs } from "pinia"
import { useScreenStore, useMainStore, useSnapshotStore } from "@/store"
import { LOCALSTORAGE_KEY_DISCARDED_DB } from "@/configs/storage"
import { deleteDiscardedDB } from "@/utils/database"
import usePptWork from "@/store/pptWork"

const usePptWorkHook = usePptWork()
const mainStore = useMainStore()
const snapshotStore = useSnapshotStore()
const screenStore = useScreenStore()
const { databaseId } = storeToRefs(mainStore)
const { screening } = storeToRefs(screenStore)

screenStore.setScreenMode("pptEditor")
if (import.meta.env.MODE !== "development") {
  // 没有保存的时候 关闭页面提示
  window.onbeforeunload = () => {
    if (!usePptWorkHook.isSave) {
      return false
    }
  }
}
// 初始化 ppt数据
usePptWorkHook.initPPTData().then(async () => {
  await deleteDiscardedDB()
  snapshotStore.initSnapshotDatabase()
})

onMounted(async () => {
  mainStore.setAvailableFonts()
})

// 应用注销时向 localStorage 中记录下本次 indexedDB 的数据库ID，用于之后清除数据库
window.addEventListener("unload", () => {
  const discardedDB = localStorage.getItem(LOCALSTORAGE_KEY_DISCARDED_DB)
  const discardedDBList: string[] = discardedDB ? JSON.parse(discardedDB) : []

  discardedDBList.push(databaseId.value)

  const newDiscardedDB = JSON.stringify(discardedDBList)
  localStorage.setItem(LOCALSTORAGE_KEY_DISCARDED_DB, newDiscardedDB)
})
</script>

<style lang="scss" scoped>
.pptEditor {
  width: 100%;
  height: 100%;
}
</style>
