<template>
  <div class="form-group micro-input-date">
    <label v-if="!!caption" :for="'inputMicro' + _uid">{{ caption }}</label>

    <input 
      :id="`inputMicroDate${_uid}`" 
      class="form-control" 
      autocomplete="off"
      :value="formattedValue" 
      :placeholder="placeholder"
      :disabled="disabled" 
      @input="handleInput" />

    <small v-if="!!description" class="form-text text-muted">
      {{ description }}
    </small>
  </div>
</template>

<script>
var Pikaday = require('pikaday-momentless').Pikaday

import { formatTimestampToDate } from '../../tools/util'
import moment from 'moment' 

export default {
  props: ['caption', 'value', 'description', 'placeholder', 'field', 'disabled', 'options', 'useTimestamp',
    'format','minDate','maxDate'],
  data() {
    return {
      pickadayInstance: false,
    }
  },

  computed: {
    formattedValue() {
      if (this.useTimestamp && this.value) {
        return this.formatTimestampToDate(this.value);
      } else {
        return this.value;
      }
    }
  },

  watch: {
    minDate(newVal) {
      if (this.pickadayInstance) {
        this.pickadayInstance.setMinDate(newVal ? new Date(newVal) : null);
      }
    },
    maxDate(newVal) {
      if (this.pickadayInstance) {
        this.pickadayInstance.setMaxDate(newVal ? new Date(newVal) : null);
      }
    }
  },

  mounted() {
    const vm = this /// ?
    let field = vm.field || {}
    let extra_options = vm.options || {}

    const format= vm.format || 'YYYY-MM-DD';

    const pickadayOptions = {
      ...extra_options,
      field: document.getElementById('inputMicroDate' + vm._uid),
      format,
      toString (date, format) {
        return moment(date).format(format);
      },
      onSelect: function() {
        if (vm.useTimestamp) {
          const selectedDate = this.getDate();
          const utcTimestamp = Date.UTC(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), 0, 0, 0, 0);
          vm.$emit('input', utcTimestamp / 1000);
          ///moment().unix
        } else {
          vm.$emit('input', moment(selectedDate).format(format));
        }
      }
    };

    if(vm.minDate) pickadayOptions.minDate = new Date(vm.minDate);
    if(vm.maxDate) pickadayOptions.maxDate = new Date(vm.maxDate);

    vm.pickadayInstance = new Pikaday(pickadayOptions);
  },

  beforeDestroy() {
    if (this.pickadayInstance && typeof this.pickadayInstance.destroy === 'function') {
      this.pickadayInstance.destroy()
    }
  },

  methods: {
    handleInput(e) {
      const vm = this
      if (!vm.useTimestamp) {
        vm.$emit('input', e.target.value);
      }
    },
    formatTimestampToDate(timestamp) {
      return formatTimestampToDate(timestamp);
    }
  }
}
</script>

<style lang="scss">
  @import '../../../node_modules/pikaday-momentless/css/pikaday.css';
</style>