<template>
  <p>Il y a {{ranges.length}} plages</p>
  <FullCalendar :options="calendarOptions"></FullCalendar>
</template>

<script setup lang="ts">

import type {CalendarOptions, DatesSetArg, EventSourceInput, EventInput} from '@fullcalendar/vue3';
import {reactive, computed, ref} from "vue";
import type {DebuggerEvent} from "vue";
import {mapGetters, useStore} from "vuex";
import {key} from './store';
import '@fullcalendar/core/vdom'; // solves problem with Vite
import frLocale from '@fullcalendar/core/locales/fr';
import FullCalendar from '@fullcalendar/vue3';
import interactionPlugin from "@fullcalendar/interaction";
import timeGridPlugin from "@fullcalendar/timegrid";

const store = useStore(key);

const baseOptions = reactive<CalendarOptions>({
  locale: frLocale,
  plugins: [interactionPlugin, timeGridPlugin],
  initialView: 'timeGridWeek',
  initialDate: new Date(),
  selectable: true,
  datesSet: onDatesSet,
  eventSources: [],
  selectMirror: false,
  editable: true,
  slotDuration: '00:15:00',
  slotMinTime: "08:00:00",
  slotMaxTime: "19:00:00",
  headerToolbar: {
    left: 'prev,next today',
    center: 'title',
    right: 'timeGridWeek timeGridDay'
  },
});

const ranges = computed<EventInput[]>(() => {
  return store.state.calendarRanges.ranges;
});

const sources = computed<EventSourceInput[]>(() => {
  const sources = [];

  const dummy: EventSourceInput = {
    id: 'dummy',
    events: [
      { id: '-1', start: '2022-06-23T12:00:00+02:00', end: '2022-06-23T14:00:00+02:00'},
      { id: '-2', start: '2022-06-24T12:00:00+02:00', end: '2022-06-24T14:00:00+02:00'},
    ]
  }

  sources.push(dummy);

  const rangeSource: EventSourceInput = {
    id: 'ranges',
    events: ranges.value,
  };

  sources.push(rangeSource);

  return sources;
});

const calendarOptions = computed((): CalendarOptions => {
  const o = {
    ...baseOptions,
    events: ranges.value,
    eventSources: sources.value,
  };

  console.log('calendarOptions', o);

  return o;
});

function onDatesSet(event: DatesSetArg) {
  store.dispatch('fullCalendar/setCurrentDatesView', {start: event.start, end: event.end})
    .then(source => {
      console.log('onDatesSet finished');
      //this.eventSources.push(source);
    });
}
</script>

<style scoped>

</style>
