<template>
  <div>
    <div v-if="isLoading">Laden...</div>
    <div v-else v-for="schedule in recurrentSchedules" :key="schedule.id">
      <span class="label-day">{{formattedDayOfWeek(schedule.selectedDay)}}</span>
      {{schedule.recurrenceStartTime.hours}}:{{formattedMinutes(schedule.recurrenceStartTime.minutes)}} -
      {{schedule.recurrenceEndTime.hours}}:{{formattedMinutes(schedule.recurrenceEndTime.minutes)}}
    </div>
    <button type="button" v-if="!isLoading" class="btn btn-primary" :class="{'mt-2': recurrentSchedules.length }" @click="openPopup">
      <span v-if="recurrentSchedules && recurrentSchedules.length">Pas schedule(s) aan</span>
      <span v-else>Voeg nieuwe schedule toe</span>
    </button>
    <recurring-schedule-picker v-model="recurrentSchedules" :version-id="version.id" :save-action="saveRecurrentSchedules" :permissions="permissions"
                               ref="recSchedulePicker"></recurring-schedule-picker>
  </div>
</template>

<style lang="scss" scoped>
  .label-day {
    display: inline-block;
    margin-right: 20px;
    width: 100px;
  }
</style>

<script>
import { mapActions } from 'vuex'
import PageApi from '../../api/page-api';
import moment from 'moment';
import recurringSchedulePicker from './recurring-schedule-picker.vue';

export default {
  props: ['version', 'permissions'],
  data () {
    return {
      recurrentSchedules: null,
    };
  },
  computed: {
    isLoading () {
      return this.recurrentSchedules === null;
    },
  },
  watch: {
    recurrentSchedules () {
      this.$emit('update:recurrentSchedules', this.recurrentSchedules);
    },
  },
  async mounted () {
    // when creating a new page, the id is not set yet
    if (this.version.id) {
      try {
        this.recurrentSchedules = await PageApi.getRecurrentSchedulesForId(this.version.id);
      } catch (e) {
        console.error('Er ging iets mis bij het ophalen van recurring schedules: ', e);
      }
    }
  },
  methods: {
    ...mapActions('alerts', [
      'addSuccess',
      'addError'
    ]),
    openPopup () {
      this.$refs.recSchedulePicker.show();
    },
    handleScheduleUpdate () {
      return Promise.all(this.recurrentSchedules.map(schedule => { // don't use index from the original array, since it is updated async
        // delete existing schedules
        if (schedule.isDeleted) {
          return PageApi.deleteSchedule(schedule.id).then(() => {
            const index = this.recurrentSchedules.findIndex(s => s.id === schedule.id);
            this.$delete(this.recurrentSchedules, index);
          });
        } else if (!schedule.id) {
          // save new schedule
          return PageApi.scheduleDaily(schedule).then(result => {
            // set id, to be sure we don't post this schedule again
            this.$set(schedule, 'id', result.id);
          });
        }
      }));
    },
    async saveRecurrentSchedules () {
      try {
        await this.handleScheduleUpdate();
        await this.addSuccess('Schedule(s) opgeslagen');
      } catch (e) {
        await this.addError(`Schedule(s) opslaan is niet gelukt <br> ${e}`);
      }
    },
    formattedDayOfWeek (day) {
      return moment(moment().locale('en').day(day)).locale('nl').format('dddd');
    },
    formattedMinutes (minutes) {
      if (minutes === 0) {
        return '00';
      } else if (minutes < 10) {
        return '0' + minutes;
      } else {
        return minutes;
      }
    },
  },
  components: {
    recurringSchedulePicker,
  },
};
</script>
