<script setup>
import dayjs from "dayjs";

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

const runningTimeInfo = ref({})

const projects = ref([])
const platform = ref("default")

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") || {}
    projects.value = await useEntities("projects").select("*")
}

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: "Projektzeit erfolgreich gestartet"})
    await setupPage()
  } catch (error) {
    console.log(error)
    toast.add({title: "Fehler beim starten der Projektzeit",color:"rose"})
  }
}

const stopStartedTime = async () => {
  try {
    await staffTime.stop()
    toast.add({title: "Projektzeit 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 Projektzeit (Fehler ID: ${errorId})` : `Fehler beim stoppen der Projektzeit`,color:"rose"})
  }
}


</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>

    <UFormGroup
        class="mt-2"
        label="Notizen:"
    >
      <UTextarea
          v-model="runningTimeInfo.notes"
      />
    </UFormGroup>
    <UFormGroup
        class="mt-2"
        label="Projekt:"
    >
      <USelectMenu
          v-model="runningTimeInfo.project"
          :options="projects"
          searchable
          :search-attributes="['name','notes','customer']"
          searchable-placeholder="Suche"
          value-attribute="id"
          option-attribute="name"
      />
    </UFormGroup>
    <UButton
        class="mt-3"
        @click="stopStartedTime"
        :disabled="!runningTimeInfo.id"
    >
      Stop
    </UButton>
  </div>
  <div v-else>
    <p>Keine Projektzeit gestartet</p>
    <UButton
        class="mt-3"
      @click="startTime"
    >Starten</UButton>
  </div>
</template>

<style scoped>

</style>
