<template>
  <modal ref="modal">
    <div class="modal-header">
      <h4 class="modal-title">Kies perioden</h4>

      <div class="form-inline mb-3 mt-3" v-if="newBlock">
        <div class="form-group">
          <select v-model="newBlock.selectedDay" class="form-control">
            <option v-for="day in daysOfWeek" :value="day.key">{{day.value}}</option>
          </select>
        </div>

        <div class="form-group ml-2">
          <select v-model="newBlock.recurrenceStartTime.hours" class="form-control">
            <option v-for="index in 24" :value="index-1">{{index-1}}</option>
          </select>
        </div>

        <div class="form-group ml-2">
          <select v-model="newBlock.recurrenceStartTime.minutes" class="form-control">
            <option v-for="index in 60" :value="index-1">{{formattedMinutes(index-1)}}</option>
          </select>
        </div>

        <div class="form-group ml-2">
          <span>tot en met</span>
        </div>

        <div class="form-group ml-2">
          <select v-model="newBlock.recurrenceEndTime.hours" class="form-control">
            <option v-for="index in 24" :value="index-1" :disabled="(index-1) < newBlock.recurrenceStartTime.hours">{{index-1}}</option>
          </select>
        </div>

        <div class="form-group ml-2">
          <select v-model="newBlock.recurrenceEndTime.minutes" class="form-control">
            <option v-for="index in 60" :value="index-1">{{formattedMinutes(index-1)}}</option>
          </select>
        </div>

        <button type="submit" class="btn btn-primary ml-2 mt-0" @click="add" :disabled="!newScheduleIsValid || !permissions.canUpdate">Voeg toe</button>
      </div>
    </div>

    <div class="modal-body">
      <div class="calendar">
        <div class="hour-labels">
          <div class="hour-label" v-for="index in 24">
            <span>{{index-1}}</span>
          </div>
        </div>

        <div class="day" v-for="(day, dayIndex) in daysOfWeek">
          <strong>{{day.value}}</strong>

          <div class="hour" v-for="index in 24">
            <div v-for="(block, blockIndex) in valueCopy"
                v-if="!block.isDeleted && block.selectedDay === daysOfWeek[dayIndex].key && block.recurrenceStartTime.hours === (index-1)"
                :style="{ height: ((block.recurrenceEndTime.hours - block.recurrenceStartTime.hours) * 20) + 'px' }"
                style="width: 100%;">
                <button type="button" class="btn-delete" @click="deleteSchedule(block, blockIndex)"><span class="icon-cross"></span></button>
              {{block.recurrenceStartTime.hours}}:{{formattedMinutes(block.recurrenceStartTime.minutes)}} - {{block.recurrenceEndTime.hours}}:{{formattedMinutes(block.recurrenceEndTime.minutes)}}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="modal-footer">
      <button class="btn" @click.prevent="cancel">Annuleren</button>
      <button class="btn btn-primary" @click.prevent="action" :disabled="!permissions.canUpdate"><span class="icon-floppy-disk"></span> Wijzigingen opslaan</button>
    </div>
  </modal>
</template>

<style lang="scss" scoped>
  .calendar {
    display: flex;
    width: 100%;
  }

  .modal-header {
    flex-wrap: wrap;
  }

  .form-inline {
    width: 100%;
  }

  .modal-body {
    max-height: 60vh;
    overflow-y: scroll;
    overflow-x: hidden;
  }

  .day {
    padding: 0 10px;
    width: calc(100% / 7);
  }

  strong + .hour {
    border-top: 1px solid grey;
    margin-top: 10px;
  }

  .hour {
    height: 20px;
    position: relative;
    border-bottom: 1px solid grey;
  }

  .hour-labels {
    padding-top: 20px; // visually align with lines of .hour
  }

  .hour-label {
    height: 20px;
  }

  .hour > div {
    position: absolute;
    left: 0;
    top: -1px; // compensate for border
    background: #3aa5e1;
    min-height: 20px;
    z-index: 1;
    padding-left: 5px;
    font-size: 12px;
  }

  .btn-delete {
    background: transparent;
    border-radius: 0 3px 3px 0;
    border: 0;
    padding: 0;
    position: absolute;
    top: 0px;
    right: -20px;
    background: white;
    width: 20px;
    height: 20px;
    color: #d9534f;
    border: 1px solid #3aa5e1;
    border-left: none;

    span {
      display: inline-block;
    }
  }
</style>

<script>
  import modal from './../modal.vue';
  import { ValueSyncMixin } from '../value-sync-mixin.js';
  import _forEachRight from 'lodash/forEachRight';

  export default {
    props: ['value','version-id','save-action', 'permissions'],
    mixins: [ValueSyncMixin],
    data() {
      return {
        valueCopy: this.value || [], // override valueSyncMixin
        newBlock: null,
        daysOfWeek: [
          {
            key: 'Monday',
            value: 'Maandag'
          },
          {
            key: 'Tuesday',
            value: 'Dinsdag'
          },
          {
            key: 'Wednesday',
            value: 'Woensdag'
          },
          {
            key: 'Thursday',
            value: 'Donderdag'
          },
          {
            key: 'Friday',
            value: 'Vrijdag'
          },
          {
            key: 'Saturday',
            value: 'Zaterdag'
          },
          {
            key: 'Sunday',
            value: 'Zondag'
          }
        ]
      };
    },
    computed: {
      newScheduleIsValid() {
        // rules:
        // 1. no: 4:00 - 3:00
        // 2. no 4:04 - 4:04
        // 3. no 4:05 - 4:04
        return this.newBlock.recurrenceEndTime.hours >= this.newBlock.recurrenceStartTime.hours &&
         !(this.newBlock.recurrenceStartTime.hours === this.newBlock.recurrenceEndTime.hours && this.newBlock.recurrenceStartTime.minutes === this.newBlock.recurrenceEndTime.minutes) &&
         !(this.newBlock.recurrenceStartTime.hours === this.newBlock.recurrenceEndTime.hours && this.newBlock.recurrenceStartTime.minutes > this.newBlock.recurrenceEndTime.minutes);
      }
    },
    mounted() {
      this.newBlock = this.getTemplate();
    },
    methods: {
      show() {
        this.$refs.modal.show();
      },
      add() {
        this.valueCopy.push(this.newBlock);
        this.newBlock = this.getTemplate();
      },
      getTemplate() {
        return {
          selectedDay: this.daysOfWeek[0].key,
          recurrenceStartTime: {
            hours: 0,
            minutes: 0
          },
          recurrenceEndTime: {
            hours: 0,
            minutes: 0
          },
          cmsPageVersionId: this.versionId
        }
      },
      action() {
        this.saveAction();
        this.$refs.modal.hide();
      },
      cancel() {
        // by forEaching from the right, we avoid a bug when more than 1 item needs to be removed.
        // The size of the array changes, so indexes aren't stable, unless we go from large to small.
        _forEachRight(this.valueCopy, (schedule, index) => {
          // cancel 'deleted' schedule
          if (schedule.isDeleted) {
            this.$delete(schedule, 'isDeleted');
          } else if (!schedule.id) {
            // delete new added schedules
            this.$delete(this.valueCopy, index);
          }
        });

        this.$refs.modal.hide();
      },
      deleteSchedule(block, blockIndex) {
        // soft delete existing schedules, deleted after save action
        if (block.id) {
          this.$set(block, 'isDeleted', true);
        } else {
          // directly delete new added schedules
          this.$delete(this.valueCopy, blockIndex);
        }
      },
      formattedMinutes(minutes) {
        if (minutes === 0) {
          return '00';
        } else if (minutes < 10) {
          return '0' + minutes;
        } else {
          return minutes;
        }
      }
    },
    components: {
      modal
    }
  }
</script>
