

<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>
    
    <!-- native date input type -->
    <template v-if="type === 'native'">
      <input type="date" 
        :name="inputname" 
        :id="inputname" 
        @change="setDateInput"/>
    </template>

    <!-- custom date input type -->
    <template v-else>
      <div class="date-input">
          <input type="tel" class="day" maxlength="2" placeholder="DD" 
              v-model="dayValue" 
              @blur="onBlur($event, 'dayValue')" 
              @focus="onFocus" 
              @keyup="onKeyUp"
              @keydown="blockNonNumerical($event)">
          <span>/</span>
          <input type="tel" class="month" maxlength="2" placeholder="MM" 
              v-model="monthValue" 
              @blur="onBlur($event, 'monthValue')" 
              @focus="onFocus" 
              @keyup="onKeyUp"
              @keydown="blockNonNumerical($event)">
          <span>/</span>
          <input type="tel" class="year" maxlength="4" placeholder="YYYY" 
              v-model="yearValue" 
              @blur="onBlur($event, 'yearValue')" 
              @focus="onFocus" 
              @keyup="onKeyUp"
              @keydown="blockNonNumerical($event)">
      </div>
    </template>

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

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

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

//import moment from 'moment'
const moment = require('moment')

export default {
  name: "dateinput",
  props: {
    inputname: {
      type: String,
      required: true
    },
    label: String,
    required: Boolean,
    minAge: Number,
    maxAge: Number,
    value: Object,
    placeholder: String,
    helpText: String,
    sectionID: Number,
    type: {
      default: "",
      type: String
    },
    customErrors: {
      type: Object,
      default: function () { 
        return {
          required: null,
          ageRange: null
        }
      }
    }
  },
  mixins: [validation],
  data() {
    return {
      dayValue: "",
      monthValue: "",
      yearValue: "",
      completeDate: 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();
      }
    });
  },
  mounted() {
    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");
    }
  },
  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, this.customErrors.required) : true,
        this.minAge && this.maxAge
          ? vRules.vrule_ageRange(this.completeDate, [this.minAge, this.maxAge], this.customErrors.ageRange)
          : true
      ];

      // check validation result
      // this function is imported from validation mixin
      // if will set the valid status and error message
      this.setValidationStatus(result, true)

      // 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, field) {
      var inputValue = this[field];
      // check value isnt a single digit and doesnt include non numerical characters
      if (inputValue.length == 1 || (inputValue.length == 2 && inputValue.match(/[a-z]/i))) {
        this[field] = inputValue.replace(/[a-z]/i, "");
        this[field] = "0" + inputValue;
      }

      // create full date object if date length correct or if user is on final input ('year')
      if (
        event.target.classList.contains("year") ||
        (this.dayValue.length == 2 &&
          this.monthValue.length == 2 &&
          this.yearValue.length == 4)
      ) {
        // set the 'completeDate' variable
        this.completeDate = this.yearValue + "/" + this.monthValue + "/" + this.dayValue;
        // validate the 'completeDate' variable
        this.validate(this.completeDate);
      }
    },
    // if the input is focused with atleast 2 characters
    // select all characters
    // to allow for easy editing
    onFocus: function(event) {
      this.isValid = null;
      if (event.target.value.length >= 2) event.target.select();
    },
    // auto tab to next input
    // if the input has correct length and is not the final input ('year')
    onKeyUp: function(event) {
      // input placeholder masking
      var inputValue = event.target.value; // get input value
      var inputValueLength = inputValue.length; // get input value length

      // skip to next input
      if (inputValueLength == 2 && inputValue.match(/^\d+$/) != null) {
        // if input has 2 characters
        if (!event.target.classList.contains("year")) {
          // if input is not last
          if (!event.shiftKey && event.keyCode != 9 && event.keyCode != 16) {
            // move focus to next input (skipping <span>/</span> tags)
            event.target.nextElementSibling.nextElementSibling.focus();
          }
        }
      }
    },
    blockNonNumerical: function (event) {
      var charCode = (typeof event.which == "undefined") ? event.keyCode : event.which;
      const charStr = String.fromCharCode(charCode);

      if (charCode == 32 || /[a-zA-Z]/.test(charStr))
        if (charCode != 97 && charCode != 98 && charCode != 99 && charCode != 100 && charCode != 101 && charCode != 102 && charCode != 103 && charCode != 104 && charCode != 105)
            event.preventDefault()
    }
  }
};
</script>
