<script>
import flatPickr from 'vue-flatpickr-component'
import { Russian } from "flatpickr/dist/l10n/ru"

export default {
  name: 'VDatepicker',
  components: {flatPickr},
  props: {
    enableTime: {
      type: Boolean,
      default: false
    },
    dateFormat: {
      type: String,
      default: null
    },
    defaultDate: {
      type: String,
      default: null
    },
    onchange: {
      type: Function,
      default: () => null
    },
    className: {
      type: String,
      default: null
    },
  },
  data() {
    return {
      date: this.parseDate(this.defaultDate),
      config: {
        wrap: true,
        altFormat: 'd.m.Y',
        altInput: true,
        dateFormat: 'm.d.Y',
        locale: Russian,      
      }
    }
  },
  computed: {  
  },
  mounted () {
    this.config.altFormat = this._dateFormat(true)
    this.config.dateFormat = this._dateFormat()
  },
  updated () {
    this.$nextTick(function () {
      if (this.defaultDate && this.defaultDate !== this.date) {
        this.date = this.parseDate(this.defaultDate)
      }
    })
  },
  methods: {
    _dateFormat (isView = false) {
      if (this.dateFormat) return this.dateFormat
      if (this.enableTime) return isView ? 'd.m.Y H:i' : 'm.d.Y H:i'
      return isView ? "d.m.Y" : 'm.d.Y'
    },
    parseDate (date) {
      if (!date) return false
      return new Date(Date.parse(date))
    }
  }
}

</script>

<template>
  <flat-pickr
    v-model="date"
    :config="config"
    :class="`!bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 flatpickr-input ${className}`"
    :onChange="(e) => onchange(e.target.value)"
  />
</template>
