<template>
    <v-menu
        v-model="visible"
        :close-on-content-click="false"
        :nudge-top="24"
        transition="scale-transition"
        offset-y
        min-width="256"
    >
        <template v-slot:activator="{ on, attrs }">
            <v-text-field
                :id="control.id"
                :hide-details="control.hideDetails"
                :dense="control.dense"
                :outlined="control.outlined"
                :clearable="control.clearable"
                :error-messages="localeErrors"
                :class="{
                    'cs-control': true,
                    'cs-date-box': true,
                }"
                append-icon="mdi-calendar"
                :persistent-hint="control.persistentHint"
                :hint="control.hint"

                :readonly="readonly"
                v-bind="attrs"
                v-on="on"

                v-model="localValue"

                @focus="$emit('focus')"
                @blur="$emit('blur')"
            >
                <template #label v-if="control.label">
                    <cs-label 
                        :control="control"
                    />
                </template>
            </v-text-field>
        </template>

        <v-date-picker
            :value="value"
            no-title
            :first-day-of-week="1"
            :locale="$locale"
            :type="type"
            @input="OnInputDatePicker"
        >
        </v-date-picker>
    </v-menu>
</template>

<script>
    import RandomString from '@CsFunc/global/RandomString';

    export default {
        props: {
            control: {required: true},

            value: {required: true},

            errors: {default: null},

            type: {default: 'date'},

            readonly: {default: true},
        },

        data: () => ({
            visible: false,
        }),

        computed: {
            localValue: {
                get: function() {
                    return this.ToDate(this.value);
                },

                set: function(value) {
                    return this.$emit('input', value);
                }
            },

            localeErrors() {
                return _.map(this.errors, error => this.__(error))
            },
        },

        methods: {
            OnInputDatePicker(value) {
                this.$emit('focus');
                setTimeout( () => {
                    this.localValue = value;
                    this.visible = false;
                }, 100);
            },
        },

        created() {
            this.control.id = 'cs-date-box-' + RandomString(64); 
        },

        components: {
            CsLabel: require('./../labels/CsLabel').default,
        },

        name: 'CsDateBox',     
        
    }
</script>