<script setup>
import {setPageLayout} from "#app";
import {useCapacitor} from "~/composables/useCapacitor.js";

definePageMeta({
  middleware: "auth",
  layout: "default",
})
const route = useRoute()
const dataStore = useDataStore()
const supabase = useSupabaseClient()

const type = route.params.type
const platform = await useCapacitor().getIsPhone() ? "mobile" : "default"
console.log(platform)


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

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

const setupPage = async () => {

  if(await useCapacitor().getIsPhone()) {
    setPageLayout("mobile")
  }

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

  if(mode.value === "show") {
    //Load Data for Show
    item.value = await useSupabaseSelectSingle(type, route.params.id, dataType.supabaseSelectWithInformation || "*")
  } else if(mode.value === "edit") {
    //Load Data for Edit
    const data = JSON.stringify((await supabase.from(type).select().eq("id", route.params.id).single()).data)
        //await useSupabaseSelectSingle(type, route.params.id)
    item.value = data

  }  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 useSupabaseSelect(type, dataType.supabaseSelectWithInformation || "*", dataType.supabaseSortColumn,dataType.supabaseSortAscending || false, true)
  }

  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"
  />
  <EntityList
      v-else-if="loaded && mode === 'list'"
      :type="type"
      :items="items"
      :platform="platform"
  />
  <UProgress
      v-else
      animation="carousel"
      class="p-5 mt-10"
  />
</template>

<style scoped>

</style>