<script setup>
import dayjs from "dayjs";

const profileStore = useProfileStore();
const toast = useToast()
const staffTime = useStaffTime()

const runningTimeInfo = ref({})

const setupPage = async () => {
    const rows = await staffTime.list({ user_id: profileStore.activeProfile?.user_id || profileStore.activeProfile?.id })
    runningTimeInfo.value = rows.find((r) => !r.stopped_at && r.type === "work") || {}
}

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 () => {
  try {
    await staffTime.start("Arbeitszeit")
    toast.add({title: "Anwesenheit erfolgreich gestartet"})
    await setupPage()
  } catch (error) {
    console.log(error)
    toast.add({title: "Fehler beim starten der Zeit",color:"error"})
  }
}

const stopStartedTime = async () => {
  try {
    await staffTime.stop()
    toast.add({title: "Anwesenheit erfolgreich gestoppt"})
    runningTimeInfo.value = {}
  } catch (error) {
    console.log(error)
    let errorId = await useError().logError(`${JSON.stringify(error)}`)
    toast.add({title: errorId ? `Fehler beim stoppen der Anwesenheit (Fehler ID: ${errorId})` : `Fehler beim stoppen der Anwesenheit`,color:"error"})
  }
}


</script>

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

    <UFormField
        class="mt-2"
        label="Notizen:"
    >
      <UTextarea
          v-model="runningTimeInfo.notes"
      />
    </UFormField>
    <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>
