<template>
  <div>
    <h2 class="chill-red">{{ $t('edit_your_calendar_range') }}</h2>
    <FullCalendar ref="fullCalendar" :options="calendarOptions">
      <template v-slot:eventContent='arg' >
        <span class='calendarRangeItems'>
        <b>{{ arg.timeText }}</b>
          <i>&nbsp;{{ arg.event.title }}</i>
          <a class="fa fa-fw fa-times"
            @click.prevent="onDelete(arg.event)">
          </a>
        </span>
      </template>
    </FullCalendar>
    <button class="btn btn-save"
      @click.prevent="onClickSave">
      {{ $t('action.save')}}
    </button>
  </div>
</template>

<script>
import '@fullcalendar/core/vdom'; // solves problem with Vite
import frLocale from '@fullcalendar/core/locales/fr';
import FullCalendar from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin from '@fullcalendar/interaction';
import timeGridPlugin from '@fullcalendar/timegrid';
import { fetchCalendar, fetchCalendarRangesByUser } from '../_api/api';

export default {
  name: "App",
  components: {
    FullCalendar
  },
  data() {
    return {
      errorMsg: [],
      userId: window.userId,
      showMyCalendar: true,
      calendarEvents: {
         userCalendar: null,
         userCalendarRange: null,
         new: {
           events: [],
           color: "#3788d8"
         }
      },
      calendarOptions: {
        locale: frLocale,
        plugins: [ dayGridPlugin, interactionPlugin, timeGridPlugin ],
        initialView: 'timeGridWeek',
        initialDate: window.startDate !== undefined ? window.startDate : new Date(),
        eventSource: [],
        selectable: true,
        select: this.onDateSelect,
        eventChange: this.onEventChange,
        eventDrop: this.onEventDropOrResize,
        eventResize: this.onEventDropOrResize,
        selectMirror: true,
        editable: true,
        weekends: false,
        headerToolbar: {
          left: 'prev,next today',
          center: 'title',
          right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
      }
    }
  },
  methods: {
    init() {
      this.fetchData()
    },
    fetchData() {
      fetchCalendarRangesByUser(this.userId).then(calendarRanges => new Promise((resolve, reject) => {
        let events = calendarRanges.results.map(i =>
          ({
            start: i.startDate.datetime,
            end: i.endDate.datetime,
            calendarRangeId: i.id
          })
        );
        let calendarRangeEvents = {
              events: events,
              color: '#79bafc',
              textColor: '#444444'
        };
        this.calendarEvents.userCalendarRange = calendarRangeEvents;

        fetchCalendar(this.userId).then(calendar => new Promise((resolve, reject) => {
          let events = calendar.results.map(i =>
            ({
              start: i.startDate.datetime,
              end: i.endDate.datetime,
            })
          );
          let calendarEventsCurrentUser = {
              events: events,
              color: 'darkblue',
              id: 1000,
              editable: false
          };
          this.calendarEvents.userCalendar = calendarEventsCurrentUser;
          this.updateEventsSource();
          resolve();
        }));

      resolve();
      }));
    },
    updateEventsSource() {
      this.calendarOptions.eventSources = [];
      this.calendarOptions.eventSources.push(this.calendarEvents.new);
      this.calendarOptions.eventSources.push(this.calendarEvents.userCalendarRange);
      if (this.showMyCalendar) {
          this.calendarOptions.eventSources.push(this.calendarEvents.userCalendar);
      }
      console.log(this.calendarOptions.eventSources);
    },
    toggleMyCalendar(value) {
      this.showMyCalendar = value;
    },
    toggleWeekends: function() {
      this.calendarOptions.weekends = !this.calendarOptions.weekends;
    },
    onDateSelect(payload) {
      let events = this.calendarEvents.new.events;
      events.push({
          start: payload.startStr,
          end: payload.endStr
      });
      this.calendarEvents.new = {
        events: events,
        color: "#3788d8"
      };
      this.updateEventsSource();
      this.$store.dispatch('createRange', payload);
    },
    onEventChange(payload) {
    },
    onEventDropOrResize(payload) {
      payload.event.setProp('color', '#3788d8');
      this.$store.dispatch('updateRange', payload);
    },
    onClickSave(payload){
      this.$store.dispatch('saveRanges', payload);
    },
    onDelete(payload){
      payload.setProp('color', '#dddddd');
      this.$store.dispatch('deleteRange', payload);
    }
  },
  mounted() {
    this.init();
  }
}
</script>
