<template>
  <div>
    <!-- Modal for adding new shows -->
    <b-modal
      id="idModalSchedules"
      ref="modalSchedules"
      title="Add/delete emission"
      size="lg"
      @ok="updateSchedules"
    >
      <p v-if="loaded.show">
        Editing schedules for <b>{{ show.name }}</b>
      </p>

      <full-calendar
        ref="calendar"
        editable="false"
        default-view="agendaWeek"
        :events="calendarSlots"
        :config="calendarConfig"
      />
    </b-modal>
  </div>
</template>

<script>
import axios from 'axios'
import {FullCalendar} from 'vue-full-calendar'
import 'fullcalendar/dist/fullcalendar.css'

export default {
  components: {
    FullCalendar,
  },
  data () {
    return {
      show: null,
      shows: [],
      timeslots: [],
      calendarSlots: [],

      // this is the whole configuration for our schedule calendar, including
      // rendering functions and all
      calendarConfig: {
        height: 600,
        firstDay: 1,
        header: {
          left: 'title',
          center: '',
          right: 'today prev,next'
        },
        views: {
          agendaWeek: {
            columnHeaderFormat: 'ddd D.M.',
            timeFormat: 'k:mm',
            slotLabelFormat: 'k:mm',
            allDaySlot: false,
          },
        },
        // here we add a simple tooltip to every event, so that the full title
        // of a show can be viewed
        eventRender: function(event, element) {
          element.attr('title', event.title);
        },
      },
      loaded: {
        show: false,
        shows: false,
        timeslots: false,
      },
    }
  },

  mounted() {
    this.$root.$on('bv::modal::shown', (bvEvent, modalId) => {
      if (this.$refs.calendar && modalId === 'idModalSchedules') {
        this.loadShows()
        this.$refs.calendar.fireMethod('render')
      }
    })
  },

  methods: {
    // opens the main modal
    open (show) {
      this.show = show
      this.loaded.show = true
      this.timeslots = []
      this.calendarSlots = []
      this.$refs.modalSchedules.show()
    },

    getShowTitleById (id) {
      let i = this.shows.findIndex(show => show.id === id)
      if (i >= 0) {
        return this.shows[i].name
      } else {
        return 'Error: no show found for this timeslot'
      }
    },

    loadTimeslots (start, end) {
      this.loaded.timeslots = false
      let uri = process.env.VUE_APP_API_STEERING + 'timeslots?start=' + start + '&end=' + end
      axios.get(uri, {
        withCredentials: true,
        headers: { 'Authorization': 'Bearer ' + this.$parent.$parent.user.access_token }
      }).then(response => {
        let slots = response.data
        for (let i in slots) {
          let highlighting = 'otherShow'
          if (slots[i].show === this.show.id) {
            highlighting = 'currentShow'
          }
          this.calendarSlots.push({
            start: slots[i].start,
            end: slots[i].end,
            title: this.getShowTitleById(slots[i].show),
            className: highlighting
          })
        }
        this.loaded.timeslots = true
      }).catch(error => {
        this.$log.error(error.response.status + ' ' + error.response.statusText)
        this.$log.error(error.response)
        alert('Error: could not load timeslots. See console for details.')
      })
    },

    loadShows () {
      this.loaded.shows = false
      let uri = process.env.VUE_APP_API_STEERING + 'shows'
      axios.get(uri, {
        withCredentials: true,
        headers: { 'Authorization': 'Bearer ' + this.$parent.$parent.user.access_token }
      }).then(response => {
        this.shows = response.data
        this.loaded.shows = true
        let start = this.$refs.calendar.fireMethod('getView').start.format()
        let end = this.$refs.calendar.fireMethod('getView').end.format()
        this.loadTimeslots(start, end)
      }).catch(error => {
        this.$log.error(error.response.status + ' ' + error.response.statusText)
        this.$log.error(error.response)
        alert('Error: could not load shows. See console for details.')
      })
    },

    updateSchedules () {
      this.$log.debug(this.$refs.calendar.fireMethod('getView').start.format())
    }
  },
}
</script>

<style>
.otherShow {
  background-color: #eee;
}
a.currentShow {
  background-color: #17a2b8;
}
</style>