<script>
import flatpickr from "flatpickr";
import { Russian } from "flatpickr/dist/l10n/ru";

export default {
  name: 'VDatepicker',
  components: {},
  inject: ['defaultDate'],
  props: {
    enableTime: {
      type: Boolean,
      default: false
    },
    dateFormat: {
      type: String,
      default: null
    },
    onchange: {
      type: Function,
      default: () => null
    },
  },
  data() {
    return {
      datepicker: null,
      value: this.defaultDate
    }
  },
  computed: {
    _dateFormat () {
      if (this.dateFormat) return this.dateFormat
      if (this.enableTime) return "d.m.Y H:i"
      return "d.m.Y"
    }
  },
  mounted () {
    this.datepicker = flatpickr(this.$refs.datepicker, {
      allowInput: true,
      enableTime: this.enableTime,
      dateFormat: this._dateFormat,
      locale: Russian,
      onChange: (a,_b,_c) => {
        this.onchange(a[0])
      }
    });
    this.datepicker.setDate(this.defaultDate)

  },
  updated() {
    this.$nextTick(function () {
      this.datepicker = flatpickr(this.$refs.datepicker, {
        allowInput: true,
        enableTime: this.enableTime,
        dateFormat: this._dateFormat,
        locale: Russian,
      });
      this.datepicker.setDate(this.value)
    })
  },
  methods: {
  }
}

</script>

<template>
  <input
    ref="datepicker"
    type="text"
    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"
  >
</template>
