<template>
    <div class="flex flex-col gap-5 mx-auto p-2 w-full max-w-md">
        <div v-if="calEvents[0]" class="flex flex-col gap-3">
            <div v-for="(event, index) in calEvents" :key="index">
                <div class="item container flex flex-col">
                    <h2 class="">{{ longEventDate(event.date) }}</h2>
                    <p class="whitespace-pre overflow-x-auto font-bold text-xl">{{ event.description}}</p>
                </div>
            </div>
        </div>
        <div class="w-full flex flex-col justify-center items-center" v-else>
            <Icon size="2em" name="ion:load-c" class="animate-spin" />
            <h2 class="mt-2 font-bold">Loading...</h2>
        </div>
    </div>
</template>

<script setup>
definePageMeta({
    title: 'Calendar'
})

const { userPersons, calEvents } = inject('firebase')

onMounted(() => {
    if (!calEvents[0]) getCalendarEvents([...new Set(userPersons.value.map(a => a.groups.join()).join().split(','))])
})

const longEventDate = (eventDate) => {
	const date = new Date(eventDate)

	return date.toLocaleString('nl-NL', {
        weekday: 'short',
        day: 'numeric',
        year: 'numeric',
        month: 'long',
        hour: 'numeric',
        minute: 'numeric'
    }
)}

const getCalendarEvents = async (group) => {

    if (!group[0]) return setTimeout(() => { getCalendarEvents([...new Set(userPersons.value.map(a => a.groups.join()).join().split(','))])}, 50)

    const events = []
    let fridayEvents = []
    let saturdayEvents = []
    let matchEvents = []

    if (group.includes('Zaterdag')){
        let data = await fetch('https://www.googleapis.com/calendar/v3/calendars/c_astg0d0auheip5o4269v1qvv3g@group.calendar.google.com/events?key=AIzaSyBLmxWNEnbkiW_0c2UrsHMbxXv73dX-KYw')
        if (!data.ok){
            throw Error('No data available')
        }

        const jsonEvents = await data.json()
        saturdayEvents = jsonEvents.items
    } if (group.includes('Vrijdag')){
        let data = await fetch('https://www.googleapis.com/calendar/v3/calendars/c_u3895n01jt8qnusm7f6pmqjb0k%40group.calendar.google.com/events?key=AIzaSyBLmxWNEnbkiW_0c2UrsHMbxXv73dX-KYw')
        if (!data.ok){
            throw Error('No data available')
        }

        const jsonEvents = await data.json()
        fridayEvents = jsonEvents.items
    } if (group.includes('Wedstrijd')){

        let data = await fetch('https://www.googleapis.com/calendar/v3/calendars/c_c2296iboq07n24galuobeesovs@group.calendar.google.com/events?key=AIzaSyBLmxWNEnbkiW_0c2UrsHMbxXv73dX-KYw')
        if (!data.ok){
            throw Error('No data available')
        }

        const jsonEvents = await data.json()
        matchEvents = jsonEvents.items
    }
        
    const allEvents = [...fridayEvents, ...saturdayEvents, ...matchEvents]

    const now = new Date()
    now.setHours(0, 0, 0, 0)

    const sortedEvents = allEvents.sort((a, b) => new Date(a.start.dateTime) - new Date(b.start.dateTime))
    const filteredEvents = sortedEvents.filter((event) => new Date(event.start.dateTime) > now )

    filteredEvents.forEach(element => {
        events.push({
            description: element.description,
            date: new Date(element.start.dateTime)
        })
    });
        
    calEvents.value = events
}

</script>