<script setup>
import dayjs from "dayjs";

const profileStore = useProfileStore();
const supabase = useSupabaseClient()
const toast = useToast()

const runningTimeInfo = ref({})

const setupPage = async () => {
    runningTimeInfo.value = (await supabase.from("workingtimes").select().eq("profile", profileStore.activeProfile.id).is("endDate", null).single()).data || {}
  console.log(runningTimeInfo.value)
}

setupPage()

/*if(dataStore.workingtimes.find(time => time.profile === profileStore.activeProfile.id && !time.endDate)) {
  runningTimeInfo.value = dataStore.workingtimes.find(time => time.profile === profileStore.activeProfile.id && !time.end)
}*/

const startTime = async () => {
  console.log("started")
  runningTimeInfo.value = {
    profile: profileStore.activeProfile.id,
    startDate: dayjs(),
    tenant: profileStore.currentTenant,
    state: "Im Web gestartet",
    source: "Dashboard"
  }

  const {data,error} = await supabase
      .from("workingtimes")
      .insert([runningTimeInfo.value])
      .select()
  if(error) {
    console.log(error)
    toast.add({title: "Fehler beim starten der Zeit",color:"rose"})
  } else if(data) {
    toast.add({title: "Anwesenheit erfolgreich gestartet"})
    runningTimeInfo.value = data[0]
    console.log(runningTimeInfo.value)
  }
}

const stopStartedTime = async () => {
  runningTimeInfo.value.endDate = dayjs()
  runningTimeInfo.value.state = "Im Web gestoppt"

  const {error,status} = await supabase
      .from("workingtimes")
      .update(runningTimeInfo.value)
      .eq('id',runningTimeInfo.value.id)

  if(error) {
    console.log(error)
    let errorId = await useError().logError(`${status} - ${JSON.stringify(error)}`)
    toast.add({title: errorId ? `Fehler beim stoppen der Anwesenheit (Fehler ID: ${errorId})` : `Fehler beim stoppen der Anwesenheit`,color:"rose"})


  } else {
    toast.add({title: "Anwesenheit erfolgreich gestoppt"})
    runningTimeInfo.value = {}
  }
}


</script>

<template>
  <div v-if="runningTimeInfo.startDate">
    <p>Start: {{dayjs(runningTimeInfo.startDate).format("HH:mm")}}</p>
    <p>Dauer: {{dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') > 59 ? `${Math.floor(dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') / 60)}:${dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') % 60} h` : dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') + ' min' }}</p>

    <UFormGroup
        class="mt-2"
        label="Notizen:"
    >
      <UTextarea
          v-model="runningTimeInfo.notes"
      />
    </UFormGroup>
    <UButton
        class="mt-3"
        @click="stopStartedTime"
        :disabled="!runningTimeInfo.id"
    >
      Stop
    </UButton>
  </div>
  <div v-else>
    <p>Keine Anwesenheit gestartet</p>
    <UButton
        class="mt-3"
      @click="startTime"
    >Starten</UButton>
  </div>
</template>

<style scoped>

</style>