<script setup>
import {setPageLayout} from "#app";

const route = useRoute()
const dataStore = useDataStore()
const api = useNuxtApp().$api


const type = route.params.type
const platform = "default"


const dataType = dataStore.dataTypes[route.params.type]

const loaded = ref(false)
const mode = ref("list")
const items = ref([])
const item = ref({})


const setupPage = async (sort_column = null, sort_direction = null) => {
  loaded.value = false
  setPageLayout(platform)

  if (type === "tasks") {
    const query = { ...route.query, mode: route.params.mode }
    if (route.params.id) query.id = route.params.id
    await navigateTo({ path: "/tasks", query })
    return
  }



  if (route.params.mode) mode.value = route.params.mode

  if (mode.value === "show") {
    //Load Data for Show
    item.value = await useEntities(type).selectSingle(route.params.id, "*", true)
  } else if (mode.value === "edit") {
    //Load Data for Edit
    item.value = JSON.stringify(await useEntities(type).selectSingle(route.params.id,"*",false))

    console.log(item.value)

  } else if (mode.value === "create") {
    //Load Data for Create
    item.value = JSON.stringify({})
    console.log(item.value)
  } else if (mode.value === "list") {
    //Load Data for List
    items.value = await useEntities(type).select({
      filters: {},
      sort: [],
      page:1
    })
  }

  loaded.value = true
}

setupPage()

</script>

<template>
  <EntityShow
      v-if="loaded && mode === 'show'"
      :type="route.params.type"
      :item="item"
      @updateNeeded="setupPage"
      :key="item"
      :platform="platform"
  />
  <EntityEdit
      v-else-if="loaded && (mode === 'edit' || mode === 'create')"
      :type="route.params.type"
      :item="item"
      :mode="mode"
      :platform="platform"
  />
  <EntityList
      :loading="!loaded"
      v-else-if="mode === 'list'"
      :type="type"
      :items="items"
      :platform="platform"
      @sort="(i) => setupPage(i.sort_column, i.sort_direction)"
  />
  <UProgress
      v-else
      animation="carousel"
      class="p-5 mt-10"
  />
</template>

<style scoped>

</style>
