<i18n>
{
  "en": {
    "april": "April",
    "august": "August",
    "blacklist": "Blacklist",
    "blacklistClients": "Blacklist Clients",
    "blacklistGroups": "Blacklist Groups",
    "clients": "Clients",
    "config": "Configuration",
    "day": "Day",
    "days": "Days",
    "december": "December",
    "description": "Description",
    "endDate": "End Date",
    "endTime": "End Time",
    "event": "Event",
    "eventName": "Event Name",
    "eventNameEmptyError": "Event Name can't be empty!",
    "eventSavedSuccess": "Event saved successfully",
    "february": "February",
    "friday": "Friday",
    "groups": "Groups",
    "groupsAndClients": "Groups / Clients",
    "id": "ID",
    "importantEvent": "Important Event",
    "interval": "Interval",
    "intervalMustBeNumberError": "Interval must be a valid number!",
    "intervalTypes": "Interval Types",
    "ip": "IP",
    "january": "January",
    "july": "July",
    "june": "June",
    "march": "March",
    "may": "May",
    "monday": "Monday",
    "month": "Month",
    "months": "Months",
    "name": "Name",
    "november": "November",
    "october": "October",
    "repetitiveModeSwitch": "repetitive Event",
    "saturday": "Saturday",
    "september": "September",
    "startDate": "Start Date",
    "startTime": "Start Time",
    "sunday": "Sunday",
    "thursday": "Thursday",
    "tuesday": "Tuesday",
    "uuid": "UUID",
    "wakeonlan": "Wake On Lan",
    "wednesday": "Wednesday",
    "week": "Week"
  },
  "de": {
    "april": "April",
    "august": "August",
    "blacklist": "Blacklist",
    "blacklistClients": "Blacklist Clienten",
    "blacklistGroups": "Blacklist Gruppen",
    "clients": "Clients",
    "config": "Konfiguration",
    "day": "Tag",
    "days": "Tage",
    "december": "Dezember",
    "description": "Beschreibung",
    "endDate": "End Datum",
    "endTime": "End Zeit",
    "event": "Veranstaltung",
    "eventName": "Veranstaltungsname",
    "eventNameEmptyError": "Der Veranstaltungsname kann nicht leer sein!",
    "eventSavedSuccess": "Event erfolgreich gespeichert",
    "february": "Februar",
    "friday": "Freitag",
    "groups": "Gruppen",
    "groupsAndClients": "Gruppen / Clients",
    "id": "ID",
    "importantEvent": "Wichtige Veranstaltung",
    "interval": "Intervall",
    "intervalMustBeNumberError": "Das Intervall muss eine gültige Zahl sein!",
    "intervalTypes": "Intervalltypen",
    "ip": "IP",
    "january": "Januar",
    "july": "Juli",
    "june": "Juni",
    "march": "März",
    "may": "Mai",
    "monday": "Montag",
    "month": "Monat",
    "months": "Monate",
    "name": "Name",
    "november": "November",
    "october": "Oktober",
    "repetitiveModeSwitch": "Wiederholende Veranstaltung",
    "saturday": "Samstag",
    "september": "September",
    "startDate": "Start Datum",
    "startTime": "Start Zeit",
    "sunday": "Sonntag",
    "thursday": "Donnerstag",
    "tuesday": "Dienstag",
    "uuid": "UUID",
    "wakeonlan": "Wake On Lan",
    "wednesday": "Mittwoch",
    "week": "Woche"
  }
}
</i18n>

<template>
  <v-card class="">
    <v-card-title style="padding: 0px; z-index: 1">
      <v-stepper v-model="step" horizontal  style="width: 100%; background: transparent;" class="elevation-3">
        <v-stepper-header>
          <v-stepper-step
            :complete="stepCompleted >= 1"
            step="1"
            :editable="stepCompleted >= 0"
            edit-icon="check"
          >
            {{ $t('event') }}
          </v-stepper-step>
          <v-divider></v-divider>
          <v-stepper-step
            :complete="stepCompleted >= 2"
            step="2"
            :editable="stepCompleted >= 1"
            edit-icon="check"
          >
            {{ $t('groupsAndClients') }}
          </v-stepper-step>
          <v-divider></v-divider>
          <v-stepper-step
            :complete="stepCompleted >= 3"
            step="3"
            :editable="stepCompleted >= 2"
            edit-icon="check"
          >
            {{ $t('blacklist') }}
          </v-stepper-step>
        </v-stepper-header>
      </v-stepper>
    </v-card-title>
    <v-card-text class="pa-0">
      <v-form v-model="valid" ref="form" @submit.prevent="submit" lazy-validation>
        <v-stepper v-model="step" horizontal style="width: 100%; background: transparent" class="elevation-0">
          <v-stepper-items>
            <v-stepper-content step="1">
              <v-layout row wrap>
                <v-flex xs12 md5>
                  <v-text-field
                    :value="name"
                    @change="name = $event"
                    :label="$t('eventName')"
                    prepend-icon="label"
                    color="primary"
                    :rules="[v => !!v || $t('eventNameEmptyError')]"
                    ref="name"
                  ></v-text-field>
                </v-flex>
                <v-flex xs12 md5 offset-md1>
                  <select-box
                    prepend-icon="device_hub"
                    :label="$t('config')"
                    v-model="config"
                    :items="configList"
                    single-select
                    :max-columns="1"
                    class="tutorial-element tutorial-no-border label-far-left label-far-bottom" style="--label-number: '1'"
                  ></select-box>
                </v-flex>
                <v-flex xs12 md5>
                  <v-textarea
                    :value="description"
                    @change="description = $event"
                    :label="$t('description')"
                    prepend-icon="description"
                    color="primary"
                    rows="1"
                    auto-grow
                  ></v-textarea>
                </v-flex>
                <v-flex xs12 md2 offset-md1>
                  <v-checkbox
                    v-model="important"
                    color="primary"
                    :label="$t('importantEvent')"
                    class="tutorial-element tutorial-no-border label-far-left label-far-bottom" style="--label-number: '2'"
                  ></v-checkbox>
                </v-flex>
                <v-flex xs12 md2 offset-md1>
                  <v-checkbox
                    v-model="wakeonlan"
                    color="primary"
                    :label="$t('wakeonlan')"
                    class="tutorial-element tutorial-no-border label-far-left label-far-bottom" style="--label-number: '3'"
                  ></v-checkbox>
                </v-flex>
              </v-layout>
              <v-layout row wrap class="tutorial-element label-right tutorial-border" style="--label-number: '4'">
                <v-flex xs12 md5>
                  <v-menu
                    v-model="startDateMenu"
                    transition="scale-transition"
                    :close-on-content-click="false"
                    lazy
                    offset-y
                    full-width
                    min-width="290px"
                  >
                    <template v-slot:activator="{ on }">
                      <v-text-field
                        v-model="startDate"
                        :label="$t('startDate')"
                        prepend-icon="event"
                        readonly
                        v-on="on"
                      ></v-text-field>
                    </template>
                    <v-date-picker color="primary" header-color="primary" v-model="startDate" @input="startDatePick()" first-day-of-week="1" :locale="locale"></v-date-picker>
                  </v-menu>
                </v-flex>
                <v-flex xs12 md5 offset-md1>
                  <v-menu
                    v-model="endDateMenu"
                    transition="scale-transition"
                    :close-on-content-click="false"
                    lazy
                    offset-y
                    full-width
                    min-width="290px"
                  >
                    <template v-slot:activator="{ on }">
                      <v-text-field
                        v-model="endDate"
                        :label="$t('endDate')"
                        prepend-icon="event"
                        readonly
                        v-on="on"
                      ></v-text-field>
                    </template>
                    <v-date-picker color="primary" header-color="primary" :min="startDate" v-model="endDate" @input="endDatePick()" first-day-of-week="1" :locale="locale"></v-date-picker>
                  </v-menu>
                </v-flex>
                <v-flex xs12 md5>
                  <v-menu
                    v-model="startTimeMenu"
                    transition="scale-transition"
                    :close-on-content-click="false"
                    lazy
                    offset-y
                    full-width
                    max-width="290px"
                    min-width="290px"
                  >
                    <template v-slot:activator="{ on }">
                      <v-text-field
                        v-model="startTime"
                        :label="$t('startTime')"
                        prepend-icon="access_time"
                        readonly
                        v-on="on"
                      ></v-text-field>
                    </template>
                    <v-time-picker
                      v-model="startTime"
                      full-width
                      format="24hr"
                      color="primary"
                      header-color="primary"
                      @click:minute="startTimeMenu = false"
                      :locale="locale"
                    ></v-time-picker>
                  </v-menu>
                </v-flex>
                <v-flex xs12 md5  offset-md1>
                  <v-menu
                    v-model="endTimeMenu"
                    transition="scale-transition"
                    :close-on-content-click="false"
                    lazy
                    offset-y
                    full-width
                    max-width="290px"
                    min-width="290px"
                  >
                    <template v-slot:activator="{ on }">
                      <v-text-field
                        v-model="endTime"
                        :label="$t('endTime')"
                        prepend-icon="access_time"
                        readonly
                        v-on="on"
                      ></v-text-field>
                    </template>
                    <v-time-picker
                      v-model="endTime"
                      :min="startDate === endDate ? startTime : '00:00'"
                      full-width
                      format="24hr"
                      color="primary"
                      header-color="primary"
                      @click:minute="endTimeMenu = false"
                      :locale="locale"
                    ></v-time-picker>
                  </v-menu>
                </v-flex>
              </v-layout>
              <v-layout row wrap>
                <v-flex>
                  <v-switch color="primary" v-model="repetitiveEvent" :label="$t('repetitiveModeSwitch')" class="tutorial-element tutorial-no-border label-left tutorial-switch" style="--label-number: '5';"/>
                </v-flex>
              </v-layout>
              <v-layout row wrap v-show="repetitiveEvent" class="">
                <v-flex xs12 md12>
                  <p class="tutorial-element tutorial-no-border tutorial-label label-right" style="margin-bottom: 0px; --label-number: '1'">{{ $t('days') }}</p>
                    <v-btn small class="no-margin" :color="dayMap[0] ? 'primary' : ''" @click="setDayMap(0)">{{ $t('monday') }}</v-btn>
                    <v-btn small class="no-margin" :color="dayMap[1] ? 'primary' : ''" @click="setDayMap(1)">{{ $t('tuesday') }}</v-btn>
                    <v-btn small class="no-margin" :color="dayMap[2] ? 'primary' : ''" @click="setDayMap(2)">{{ $t('wednesday') }}</v-btn>
                    <v-btn small class="no-margin" :color="dayMap[3] ? 'primary' : ''" @click="setDayMap(3)">{{ $t('thursday') }}</v-btn>
                    <v-btn small class="no-margin" :color="dayMap[4] ? 'primary' : ''" @click="setDayMap(4)">{{ $t('friday') }}</v-btn>
                    <v-btn small class="no-margin" :color="dayMap[5] ? 'primary' : ''" @click="setDayMap(5)">{{ $t('saturday') }}</v-btn>
                    <v-btn small class="no-margin" :color="dayMap[6] ? 'primary' : ''" @click="setDayMap(6)">{{ $t('sunday') }}</v-btn>
                </v-flex>
                <v-flex xs12 md12 style="margin-top: 20px; margin-bottom: 20px">
                  <p class="tutorial-element tutorial-no-border tutorial-label label-right" style="margin-bottom: 0px; --label-number: '2'">{{ $t('months') }}</p>
                    <v-btn small class="no-margin" :color="monthMap[0] ? 'primary' : ''" @click="setMonthMap(0)">{{ $t('january') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[1] ? 'primary' : ''" @click="setMonthMap(1)">{{ $t('february') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[2] ? 'primary' : ''" @click="setMonthMap(2)">{{ $t('march') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[3] ? 'primary' : ''" @click="setMonthMap(3)">{{ $t('april') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[4] ? 'primary' : ''" @click="setMonthMap(4)">{{ $t('may') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[5] ? 'primary' : ''" @click="setMonthMap(5)">{{ $t('june') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[6] ? 'primary' : ''" @click="setMonthMap(6)">{{ $t('july') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[7] ? 'primary' : ''" @click="setMonthMap(7)">{{ $t('august') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[8] ? 'primary' : ''" @click="setMonthMap(8)">{{ $t('september') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[9] ? 'primary' : ''" @click="setMonthMap(9)">{{ $t('october') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[10] ? 'primary' : ''" @click="setMonthMap(10)">{{ $t('november') }}</v-btn>
                    <v-btn small class="no-margin" :color="monthMap[11] ? 'primary' : ''" @click="setMonthMap(11)">{{ $t('december') }}</v-btn>
                </v-flex>
                <v-flex xs12 md5>
                  <v-text-field
                    v-model="interval"
                    :label="$t('interval')"
                    prepend-icon="repeat"
                    color="primary"
                    type="number"
                    min="1"
                    :rules="[() => !!interval || $t('intervalMustBeNumberError')]"
                    class="tutorial-element tutorial-no-border label-top" style="--label-number: '3'"
                  ></v-text-field>
                </v-flex>
                <v-flex xs12 md5 offset-md1>
                  <v-select :items="intervalTypes" :label="$t('intervalTypes')" item-text="name" v-model="intervalType" prepend-icon="repeat" color="primary" offset-y class="tutorial-element tutorial-no-border label-top" style="--label-number: '4'"></v-select>
                </v-flex>
              </v-layout>
            </v-stepper-content>

            <v-stepper-content step="2" class="stepper-padding-0">
              <v-tabs v-if="step == 2" v-model="tabs" grow slider-color="primary">
                <v-tab><div class="tutorial-element tutorial-no-border label-far-left" style="--label-number: '1'"><v-icon class="tabbar-tabicon">category</v-icon></div>{{ groups.length + ' ' + $t('groups') }}</v-tab>
                <v-tab><div class="tutorial-element tutorial-no-border label-far-left" style="--label-number: '2'"><v-icon class="tabbar-tabicon">computer</v-icon></div>{{ clients.length + ' ' + $t('clients') }}</v-tab>
                <v-tab-item>
                  <data-table v-model="groups" :headers="groupHeaders" :items="groupList"/>
                </v-tab-item>
                <v-tab-item>
                  <data-table v-model="clients" :headers="clientHeaders" :items="clientList"/>
                </v-tab-item>
              </v-tabs>
            </v-stepper-content>

            <v-stepper-content step="3" class="stepper-padding-0">
              <v-tabs v-if="step == 3" v-model="tabs" grow slider-color="primary">
                <v-tab><v-icon class="tabbar-tabicon">category</v-icon>{{ blacklistGroups.length + ' ' + $t('blacklistGroups') }}</v-tab>
                <v-tab><v-icon class="tabbar-tabicon">computer</v-icon>{{ blacklistClients.length + ' ' + $t('blacklistClients') }}</v-tab>
                <v-tab-item>
                  <data-table v-model="blacklistGroups" :headers="groupHeaders" :items="blackgroupList"/>
                </v-tab-item>
                <v-tab-item>
                  <data-table v-model="blacklistClients" :headers="clientHeaders" :items="blackclientList"/>
                </v-tab-item>
              </v-tabs>
            </v-stepper-content>

          </v-stepper-items>
        </v-stepper>
      </v-form>
    </v-card-text>
    <v-divider></v-divider>
    <v-card-actions>
      <v-spacer></v-spacer>
      <v-btn flat @click.native="$store.commit('events/setDialog', { show : false } )">{{ $t('cancel') }}</v-btn>
      <v-btn :color="dialog.info.id ? 'primary' : 'success'" @click="submit" type="submit">{{ dialog.info.id ? $t('save') : $t('create') }}</v-btn>
      <v-btn color="primary" v-show="step == 1" @click.native="completeStepOne()">{{ $t('continue') }}</v-btn>
      <v-btn color="primary" v-show="step == 2 && groups.length > 0" @click.native="completeStepTwo()">{{ $t('continue') }}</v-btn>
    </v-card-actions>
  </v-card>
</template>

<script>
import SelectBox from '@/components/SelectBox'
import DataTable from '@/components/DataTable'
import { mapState } from 'vuex'

export default {
  name: 'EventModuleEdit',
  components: {
    SelectBox,
    DataTable
  },
  data () {
    return {
      tabs: 0,
      startDate: '',
      endDate: '',
      startTime: '',
      endTime: '',
      startDateMenu: false,
      endDateMenu: false,
      startTimeMenu: false,
      endTimeMenu: false,
      repetitiveEvent: false,
      dayMap: [],
      monthMap: [],
      interval: 1,
      intervalType: '',
      valid: true,
      step: 1,
      stepCompleted: 0,
      name: '',
      description: '',
      important: false,
      wakeonlan: false,
      config: [],
      times: {},
      groups: [],
      blacklistGroups: [],
      blackgroupList: [],
      clients: [],
      blacklistClients: [],
      blackclientList: [],
      clientHeaders: [
        { text: this.$t('name'), key: 'name' },
        { text: this.$t('ip'), key: 'ip' },
        { text: this.$t('uuid'), key: 'uuid' }
      ],
      groupHeaders: [
        { text: this.$t('id'), key: 'id' },
        { text: this.$t('name'), key: 'name' },
        { text: this.$t('description'), key: 'description' }
      ],
      intervalTypes: []
    }
  },
  computed: {
    ...mapState('events', ['dialog', 'configList']),
    ...mapState('groups', ['groupList', 'clientList']),
    locale () { return this.$store.state.settings.locale }
  },
  watch: {
    step (val) {
      if (val === '3') this.loadChilds()
    },
    dialog: {
      immediate: true,
      deep: true,
      handler (value) {
        if (value.type === 'edit' && value.show) {
          if (this.$refs.form) this.$refs.form.resetValidation()
          this.step = 1
          this.tabs = 0
          this.intervalTypes = [
            { name: this.$t('day'), value: 'day' },
            { name: this.$t('week'), value: 'week' },
            { name: this.$t('month'), value: 'month' }
          ]
          this.stepCompleted = value.info.id ? 4 : 0
          this.name = value.info.name || ''
          this.description = value.info.description || ''
          this.important = value.info.important || false
          this.wakeonlan = value.info.wakeonlan || false

          this.config = value.info.config ? [value.info.config] : []

          this.times = value.info.times ? JSON.parse(value.info.times) : {}
          this.repetitiveEvent = this.times.repetitive || false
          var start
          var end
          if (this.repetitiveEvent) {
            // edit of repetitive event
            start = this.times.start.split(' ')
            end = this.times.end.split(' ')
            this.startDate = start[0]
            this.endDate = end[0]
            this.startTime = start[1]
            this.endTime = end[1]
          } else if (value.info.times) {
            // edit of non repetitive event
            start = this.times.start.split(' ')
            end = this.times.end.split(' ')
            this.startDate = start[0]
            this.endDate = end[0]
            this.startTime = start[1]
            this.endTime = end[1]
          } else {
            // create new event
            this.startDate = this.formatDate(new Date(), { time: false })
            this.endDate = this.formatDate(new Date(), { time: false })
            this.startTime = '00:00'
            this.endTime = '23:59'
          }
          this.interval = this.times.interval || 1
          this.intervalType = this.times.intervalType || this.intervalTypes[0].value
          this.dayMap = this.times.dayMap || [1, 1, 1, 1, 1, 1, 1]
          this.monthMap = this.times.monthMap || [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

          if (value.info.groups) {
            this.groups = []
            this.clients = []
            var groupsPush = []
            var clientsPush = []
            for (let i = 0; i < value.info.groups.length; i++) {
              if (value.info.groups[i].group_x_event.blacklist) groupsPush.push(value.info.groups[i])
              else this.groups.push(value.info.groups[i])
            }
            for (let i = 0; i < value.info.clients.length; i++) {
              if (value.info.clients[i].client_x_event.blacklist) clientsPush.push(value.info.clients[i])
              else this.clients.push(value.info.clients[i])
            }
            this.loadChilds().then(() => {
              this.blacklistGroups = groupsPush
              this.blacklistClients = clientsPush
            })
          } else {
            this.groups = []
            this.clients = value.info.clients ? value.info.clients : []
            this.blacklistGroups = []
            this.blacklistClients = []
            this.blackgroupList = []
            this.blackclientList = []
          }
        }
      }
    }
  },
  methods: {
    formatDate (date, options = {}) {
      var result = ''
      const pad = x => x < 10 ? '0' + x : x
      if (options.date !== false) {
        result += date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate())
      }
      if (options.time !== false) {
        if (result !== '') result += ' '
        result += pad(date.getHours()) + ':' + pad(date.getMinutes())
        if (options.seconds !== false) result += ':' + pad(date.getSeconds())
      }
      return result
    },
    completeStepOne () {
      if (this.$refs.form.validate()) {
        this.step = 2
        this.stepCompleted = Math.max(1, this.stepCompleted)
      }
    },
    completeStepTwo () {
      this.loadChilds()
      this.step = 3
      this.stepCompleted = Math.max(2, this.stepCompleted)
    },
    async submit (event) {
      if (this.$refs.form.validate()) {
        // Build times object
        var start
        var end
        if (this.repetitiveEvent) {
          start = this.startDate + ' ' + this.startTime
          end = this.endDate + ' ' + this.endTime
          this.times = {
            'repetitive': true,
            'start': start,
            'end': end,
            'dayMap': this.dayMap,
            'monthMap': this.monthMap,
            'interval': this.interval,
            'intervalType': this.intervalType
          }
        } else {
          start = this.startDate + ' ' + this.startTime
          end = this.endDate + ' ' + this.endTime
          this.times = {
            'repetitive': false,
            'start': start,
            'end': end
          }
        }
        await this.loadChilds()
        // Submit
        const url = this.dialog.info.id === undefined ? '/api/events' : '/api/events/' + this.dialog.info.id
        await this.$http.post(url, {
          name: this.name,
          description: this.description,
          groups: this.groups.map(x => x.id),
          blacklistGroups: this.blacklistGroups.map(x => x.id),
          clients: this.clients.map(x => x.id),
          blacklistClients: this.blacklistClients.map(x => x.id),
          config: this.config.map(x => x.id),
          important: this.important,
          wakeonlan: this.wakeonlan,
          times: JSON.stringify(this.times)
        })
        this.$store.dispatch('events/loadEvents')
        this.$store.commit('events/setDialog', { show: false })
        this.$snackbar({ color: 'success', text: this.$t('eventSavedSuccess') })
      } else {
        this.$snackbar({ color: 'error', text: this.$t('eventNameEmptyError') })
      }
    },
    startDatePick () {
      this.startDateMenu = false
      if (this.startDate > this.endDate) {
        this.endDate = this.startDate
      }
    },
    endDatePick () {
      this.endDateMenu = false
      if (this.endTime < this.startTime) {
        this.endTime = this.startTime
      }
    },
    setDayMap (i) {
      this.$set(this.dayMap, i, this.dayMap[i] ? 0 : 1)
    },
    setMonthMap (i) {
      this.$set(this.monthMap, i, this.monthMap[i] ? 0 : 1)
    },
    async loadChilds () {
      if (this.groups.length > 0) {
        var response = await this.$http.post('/api/events/blacklist', { groups: this.groups })
        this.blackgroupList = response.data.subgroups
        this.blackclientList = response.data.clients
        this.blacklistGroups = this.blacklistGroups.filter(g => this.blackgroupList.map(x => x.id).indexOf(g.id) !== -1)
        this.blacklistClients = this.blacklistClients.filter(c => this.blacklistClients.map(x => x.id).indexOf(c.id) !== -1)
      } else {
        this.blackgroupList = []
        this.blackclientList = []
        this.blacklistGroups = []
        this.blacklistClients = []
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.no-margin {
  margin-right: 0px;
  margin-left: 0px;
}
.stepper-padding-0 {
  padding: 0;
}
</style>
