<script setup lang="ts">
import ClockHeader from "@/components/header/partials/ClockHeader.vue";
import ClockContent from "@/components/header/partials/ClockContent.vue";
import axios, {type AxiosResponse} from "axios";
import {DateTime} from "luxon";
import {onMounted, reactive, ref} from "vue";
import {useAuthStore} from "@/stores/auth.store.ts";

const auth = useAuthStore();

const now = ref(DateTime.now());

const clockHour = reactive({
  start: now.value.set({minute: 0}).setZone(import.meta.env.VITE_APP_TIMEZONE),
  end: now.value.set({minute: 0}).plus({hours: 1}).setZone(import.meta.env.VITE_APP_TIMEZONE)
});

const items = ref([]);

const getItems = async (): void => {
  return await axios.get('showInstances', {
    params: {
      date_range: {
        start: clockHour.start.toISO(),
        end: clockHour.end.toISO()
      }
    }
  }).then((response): AxiosResponse => {
    items.value = response.data
  })
}

const changeHour = (value): void => {
  switch (value) {
    case 'prev':
      clockHour.start = clockHour.start.minus({ hours: 1});
      clockHour.end = clockHour.end.minus({ hours: 1});
      break;
    case 'next':
      clockHour.start = clockHour.start.plus({ hours: 1});
      clockHour.end = clockHour.end.plus({ hours: 1});
      break;
  }
  getItems();
}

onMounted((): void => {
  getItems();
});
</script>

<template>
  <v-card>
    <ClockHeader
        :time="clockHour.start.setZone(auth.timezone).toFormat('H:mm')"
        @change-clock="changeHour"
    />
    <ClockContent v-if="items.length > 0" v-for="item in items" :key="item.id" :item="item" />
    <v-card-text v-else>
      {{ $t('header.clock.nothingfound') }}
    </v-card-text>
  </v-card>
</template>

<style scoped>
  .v-card {
    min-width: 25vw;
  }
</style>