<template>
  <div class="question" v-bind:class="{ 
      'error': isValid == false, 
      'good': isValid == true
    }">
    <label v-show="label !== null && label !== ''">{{ label }}</label>
    <span class="info-message" v-if="helpText !== undefined">{{ helpText }}</span>
    <span class="input-select input-month">
      <span>Month</span>
      <select
        v-model="monthValue"
        placeholder="Month..."
        v-bind:class="{ 
          'error': isValid == false, 
          'good': isValid == true
        }"
        @change="onBlur"
        @focus="isValid = null"
      > 
        <option value="Month..." selected hidden>Month...</option>
        <option value="01">January</option>
        <option value="02">February</option>
        <option value="03">March</option>
        <option value="04">April</option>
        <option value="05">May</option>
        <option value="06">June</option>
        <option value="07">July</option>
        <option value="08">August</option>
        <option value="09">September</option>
        <option value="10">October</option>
        <option value="11">November</option>
        <option value="12">December</option>
      </select>
    </span>
    <span class="input-select input-year">
      <span>Year</span>
      <select
        v-model="yearValue"
        placeholder="Year..."
        v-bind:class="{ 
          'error': isValid == false, 
          'good': isValid == true
        }"
        @change="onBlur"
        @focus="isValid = null"
      > 
        <option value="Year..." selected hidden>Year...</option>
        <template v-for="year in yearOptions">
          <option 
          :key="year" 
          :value="year.toString()" 
          :selected="yearValue === year"
          >{{ year }}</option>
        </template>
      </select>
    </span>

    <!--<span class="input-year">
      <span>Year</span>
      <input type="tel" class="year yearCalc" maxlength="4" placeholder="YYYY" v-model="yearValue" @blur="onBlur" />
    </span>-->

    <span class="error-message" v-html="validationMessage"></span>

    <template v-if="timeSpent !== null">
      <span class="info-message supporting-below" v-show="yearsSince">
          {{ timeSpent.prefix }} <strong>{{ yearsSince }}</strong> {{ timeSpent.postfix }}
      </span>
    </template>
  </div>
</template>

<script>
// create event hub for validation events
import Vue from 'vue'
//import EventHub from 'vue-event-hub'
//Vue.use(EventHub)

const moment = require('moment')

import vRules from 'vanilla-validation'
import { validation } from '../mixins/validation.js'

export default {
  name: 'monthyearinput',
  props: {
    inputname: {
      type: String,
      required: true
    },
    label: String,
    required: Boolean,
    value: Object,
    helpText: String,
    timeSpent: Object,
    sectionID: Number,
    settings: Object
  },
  mixins: [validation],
  data() {
    return {
      dayValue: '01',
      monthValue: '',
      yearValue: '',
      completeDate: null,
      yearOptions: []
    }
  },
  watch: {
    settings: function(newSettings, oldSettings){
      // if settings prop changes
      // check settings prop and build year options array list
      if (newSettings !== oldSettings)
        this.checkSettings(newSettings)
    }
  },
  computed: {
    yearsSince: function () {
      if (this.completeDate != null) {
        let completeDate = moment(this.completeDate, "YYYY/MM/DD")
        return moment().diff(completeDate, "years")
      } else {
        return null
      }
    }
  },
  created() {
    // We listen for the event on the eventHub
    this.$eventHub.on('validate', (id) => {
      // if validating by section
      if (this.sectionID != undefined) {
          // if the id provided matches section ID then validate
          if (id === this.sectionID) {
            this.validate()
          }
      } else {
        // if not validating by section
        this.validate()
      }
    })
    // check settings prop and build year options array list
    this.checkSettings(this.settings)
  },
  mounted() {
    // if prepopulating add data and valdiate
    if (this.value !== null && this.value !== undefined) {
        // set commplete date for validation
        this.completeDate = moment(this.value.value, "YYYY/MM/DD")
        // split date into DD MM YYYY for individual inputs
        let passedDateArray = this.completeDate
        this.dayValue = passedDateArray.date()
        this.monthValue = passedDateArray.month()
        this.yearValue = passedDateArray.year()

        this.validate('prepopulated')
    } else {
        this.monthValue = 'Month...'
        this.yearValue = 'Year...'
    }
  },
  methods: {
    emitValue: function(type){
      // emit validated event
      this.$emit(type, { 
        'value': moment(this.completeDate, "YYYY/MM/DD").format("YYYY/MM/DD"), 
        'name': this.inputname, 
        'isValid': this.isValid
      })
    },
    validate: function(type) {
      // check what validations are required
      // and build and array of booleans (these are then checked to see if input is valid)
      let result = [
        // default input type validation rule
        vRules.vrule_date(this.completeDate),
        // conditional validation rules
        this.required ? vRules.vrule_date_required(this.completeDate) : true
      ]     
      
      // check validation result
      // this function is imported from validation mixin
      // if will set the valid status and error message
      this.setValidationStatus(result)

      // default the type to 'validated' if not using prepopulated event type
      let emitType = type !== 'prepopulated' ? 'validated' : type
      // emit the updated value to parent
      this.emitValue(emitType)
    },

    onBlur: function(event){
      /*if (event.target.value.length == 1 || (event.target.value.length == 2 && event.target.value.match(/[a-z]/i))) {
          event.target.value = event.target.value.replace(/[a-z]/i, "")
          event.target.value = "0" + event.target.value;
      }*/

      if (this.dayValue.length == 2 && this.monthValue.length == 2 && this.yearValue.length == 4) {
          // update form control value
          this.completeDate = this.yearValue + "/" + this.monthValue + "/" + this.dayValue
          this.validate(this.completeDate)
      }
    },
    checkSettings: function(settings){
      let YearsArray
      if (settings !== null && settings !== undefined) {
        YearsArray = this.calculateYearOptions(settings.start, settings.end)
      } else {
        YearsArray = this.calculateYearOptions(
          {
            date: moment().substract(100, 'years').format("YYYY/MM/DD"), 
            format: "YYYY/MM/DD"
          }, {
            date: moment().format("YYYY/MM/DD"), 
            format: "YYYY/MM/DD"
          }
        )
      }
      this.yearOptions = YearsArray
    },
    calculateYearOptions: function (startYear, endYear) {
      let startDate = moment(startYear.date, startYear.format).year()
      let endDate = moment(endYear.date, endYear.format).year()
      let yearsArray = []

      // push years to array
      for(let i = startDate; i <= endDate; i++) {
        yearsArray.push(i);
      }
      
      return yearsArray
    }
  }
}
</script>
