<script setup>
import deLocale from "@fullcalendar/core/locales/de";
import FullCalendar from "@fullcalendar/vue3";
import dayGridPlugin from "@fullcalendar/daygrid"
import timeGridPlugin from "@fullcalendar/timegrid"
import resourceTimelinePlugin from "@fullcalendar/resource-timeline";
import interactionPlugin from "@fullcalendar/interaction";
import dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})

//Config
const route = useRoute()
const router = useRouter()
const mode = ref(route.params.mode || "grid")
const supabase = useSupabaseClient()
const dataStore = useDataStore()
const resources = dataStore.getResources
const eventTypes = dataStore.getEventTypes


//Working
const newEventData = ref({
  resources: [],
  resourceId: "",
  resourceType: "",
  title: "",
  type: "Umsetzung",
  start: "",
  end: null
})
const showNewEventModal = ref(false)
const showEventModal = ref(false)
const selectedEvent = ref({})
const selectedResources = ref([])


//Functions
const convertResourceIds = () => {

  newEventData.value.resources = selectedResources.value.map(i => {
    /*if(i.type !== 'Mitarbeiter') {
      return {id: Number(i.id.split('-')[1]), type: i.type}
    } else {
      return {id: i.id, type: i.type}
    }*/

    if((String(i).match(/-/g) || []).length > 1) {
      return {type: "Mitarbeiter", id: i}
    } else {

      if(i.split('-')[0] === 'I') {
        return {id: Number(i.split('-')[1]), type: "Inventar"}
      } else if(i.split('-')[0] === 'F') {
        return {id: Number(i.split('-')[1]), type: "Fahrzeug"}
      }
    }


  })
}

//Calendar Config
const calendarOptionsGrid = reactive({
  locale: deLocale,
  plugins: [dayGridPlugin, interactionPlugin, timeGridPlugin],
  headerToolbar: {
    left: 'prev,next today',
    center: 'title',
    right: 'dayGridMonth,timeGridWeek,timeGridDay'
  },
  initialView: "dayGridMonth",
  initialEvents: dataStore.getEvents,
  nowIndicator: true,
  height: "80vh",
  selectable: true,
  weekNumbers: true,
  select: function(info) {
    console.log(info)


    router.push(`/events/edit/?start=${info.startStr}&end=${info.endStr}&source=grid`)

  },
  eventClick: function (info){
    console.log(info)
    if(info.event.title.startsWith("Abw.:")){
      router.push(`/absencerequests/show/${info.event.id}`)
    } else {
      router.push(`/events/show/${info.event.id}`)
    }

  },
})

const calendarOptionsTimeline = reactive({
  schedulerLicenseKey: "CC-Attribution-NonCommercial-NoDerivatives",
  locale: deLocale,
  plugins: [resourceTimelinePlugin, interactionPlugin],
  initialView: "resourceTimeline3Hours",

  headerToolbar: {
    left: 'prev,next',
    center: 'title',
    right: 'resourceTimelineDay,resourceTimeline3Hours,resourceTimelineMonth'
  },
  initialEvents: dataStore.getEventsByResource,
  selectable: true,
  select: function (info) {
    router.push(`/events/edit/?start=${info.startStr}&end=${info.endStr}&resources=${JSON.stringify([info.resource.id])}&source=timeline`)
  },
  eventClick: function (info){
    if(info.event.title.startsWith("Abw.:")){
      router.push(`/absencerequests/show/${info.event.id}`)
    } else {
      router.push(`/events/show/${info.event.id}`)
    }
  },
  resourceGroupField: "type",
  resourceOrder: "-type",
  resources: resources,
  nowIndicator:true,
  views: {
    resourceTimeline3Hours: {
      type: 'resourceTimeline',
      slotDuration: {hours: 3},
      slotMinTime: "06:00:00",
      slotMaxTime: "21:00:00",
      /*duration: {days:7},*/
      buttonText: "Woche",
      visibleRange: function(currentDate) {
        // Generate a new date for manipulating in the next step
        var startDate = new Date(currentDate);
        var endDate = new Date(currentDate);

        // Adjust the start & end dates, respectively
        startDate.setDate(startDate.getDate() - startDate.getDay() +1); // One day in the past
        endDate.setDate(startDate.getDate() + 5); // Two days into the future

        return { start: startDate, end: endDate };
      }
    }
  },
  height: '80vh',
})

</script>

<template>
  <UDashboardNavbar :title="currentItem ? currentItem.name : ''">
    <template #right>

    </template>
  </UDashboardNavbar>

  <div v-if="mode === 'grid'" class="p-5">
    <FullCalendar
        :options="calendarOptionsGrid"
    />
  </div>
  <div v-else-if="mode === 'timeline'" class="p-5">
    <FullCalendar
        :options="calendarOptionsTimeline"
    />
  </div>
</template>

<style scoped>

</style>