<template>
    <input type="text"
        :id="id"
        :name="name"
        :class="inputClass"
        :placeholder="placeholder"
        @change="(event) => updateDate(event.target.value)"
    />
</template>
<script>
    import moment from 'moment';
    export default {
        props: {
            inputClass: {
                type: String,
                default: ''
            },
            id: String,
            name: String,
            placeholder: String,
            value: String,
            disabledDates: {
                type: Array,
                default: () => { return []; }
            },
            options: {
                type: Object,
            }
        },
        methods: {
            updateDate(date) {
                this.$emit('input', date);
            },
            defaults() {
                // define some defaults
                let defaults = {
                    showButtonPanel: true,
                    dateFormat: 'dd/mm/yy',
                    onSelect: (date) => this.updateDate(date), // on select run updateDate function
                    beforeShowDay: function (date) {
                        let string = moment(date).format('D/M/Y');
                        // if disabledDates is defined then indexOf it else indexOf empty string
                        return [ (this.disabledDates || '').indexOf(string) == -1 ]
                    }
                };

                return Object.assign({}, defaults, this.options);
            }
        },
        mounted() {
            let vm = this,
                $el = vm.$el;

            if (vm.value) {
                $el.value = vm.value;
            }
            $($el).datepicker(vm.defaults());
        },
        beforeDestroy() {
            $(this.$el).datepicker('hide')
                .datepicker('destroy');
        },
        watch: {
            value() {
                let vm = this,
                    $el = vm.$el;

                $el.value = vm.value;
                $($el).datepicker('refresh');
            }
        }
    }
</script>
