<script setup>
import { ref, watch } from 'vue';
import EntityCalendarGrid from 'src/components/EntityCalendarGrid.vue';
import VehicleCalendar from './VehicleCalendar.vue';
import { useArrayData } from 'src/composables/useArrayData';

const props = defineProps({
    dataKey: {
        type: String,
        required: true,
    },
});

const firstDay = ref(new Date());
const lastDay = ref(new Date());
const entityCalendarRef = ref(null);

const arrayData = useArrayData(props.dataKey);
const { store } = arrayData;
const _data = ref(null);
const days = ref({});
const events = ref([]);

const refreshEvents = () => {
    days.value = {};
    if (!events.value?.length || !firstDay.value || !lastDay.value) return;

    let day = new Date(firstDay.value.getTime());
    let endDate = new Date(lastDay.value.getTime());

    while (day <= endDate) {
        let stamp = day.getTime();
        let dayEvents = [];

        for (let event of events.value) {
            const eventStart = event.started ? new Date(event.started).getTime() : null;
            const eventEnd = event.finished ? new Date(event.finished).getTime() : null;

            let match =
                (!eventStart || stamp >= eventStart) && (!eventEnd || stamp <= eventEnd);

            if (match) {
                dayEvents.push(event);
            }
        }

        if (dayEvents.length) {
            days.value[stamp] = dayEvents;
        }

        day.setDate(day.getDate() + 1);
    }
};

watch(
    () => store.data,
    (value) => {
        _data.value = value;
        events.value = Array.isArray(value) ? value : [];

        function toStamp(date) {
            return date && new Date(date).setHours(0, 0, 0, 0);
        }

        if (events.value) {
            for (let event of events.value) {
                event.dated = toStamp(event.dated);
                event.finished = toStamp(event.finished);
                event.started = toStamp(event.started);
            }
        }

        refreshEvents();
    },
    { immediate: true },
);

watch(
    () => entityCalendarRef.value?.firstDay,
    (newVal) => {
        if (newVal) firstDay.value = new Date(newVal);
    },
);

watch(
    () => entityCalendarRef.value?.lastDay,
    (newVal) => {
        if (newVal) lastDay.value = new Date(newVal);
    },
);
</script>

<template>
    <EntityCalendarGrid
        ref="entityCalendarRef"
        :data-key="dataKey"
        :calendar-component="VehicleCalendar"
        :additional-props="{ daysMap: days }"
        @refresh-events="refreshEvents"
        v-bind="$attrs"
    />
</template>
