<template>
    <div class="control">
        <input type="hidden" :name="name" :value="selectedValue"
            @change="$emit('change', $event)"/>
        <input type="text" ref="input" class="input is-fullwidth" :class="inputClass"
            v-show="!button || !selected"
            v-model="inputValue"
            :placeholder="placeholder"
            @keydown.capture="onKeyDown"
            @keyup="onKeyUp($event); $emit('keyup', $event)"
            @keydown="$emit('keydown', $event)"
            @keypress="$emit('keypress', $event)"
            @focus="onInputFocus" @blur="onBlur" />
        <a v-if="selected && button"
                class="button is-normal is-fullwidth has-text-left is-inline-block overflow-hidden"
                @click="select(-1, false, true)">
            <span class="icon is-small ml-1">
                <i class="fa fa-pen"></i>
            </span>
            <span class="is-inline-block" v-if="selected">
                <slot name="button" :index="selectedIndex" :item="selected"
                    :value-field="valueField" :labelField="labelField">
                {{ labelField && selected.data[labelField] || selected }}
                </slot>
            </span>
        </a>
        <div :class="dropdownClass">
            <div class="dropdown-menu is-fullwidth">
                <div class="dropdown-content" style="overflow: hidden">
                    <a v-for="(item, index) in items" :key="item.id"
                        href="#" :data-autocomplete-index="index"
                        @click="select(index, false, false)"
                        :class="['dropdown-item', (index == this.cursor) ? 'is-active':'']"
                        :title="labelField && item.data[labelField] || item"
                        tabindex="-1">
                        <slot name="item" :index="index" :item="item" :value-field="valueField"
                            :labelField="labelField">
                        {{ labelField && item.data[labelField] || item }}
                        </slot>
                    </a>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
// import debounce from 'lodash/debounce'
import Model from '../model'


export default {
    emit: ['change', 'keypress', 'keydown', 'keyup', 'select', 'unselect',
           'update:modelValue'],

    props: {
        //! Search URL (where `${query}` is replaced by search term)
        url: String,
        //! Items' model
        model: Function,
        //! Input tag class
        inputClass: Array,
        //! input text placeholder
        placeholder: String,
        //! input form field name
        name: String,
        //! Field on items to use as label
        labelField: String,
        //! Field on selected item to get selectedValue from, if any
        valueField: {type: String, default: null},
        count: {type: Number, count: 10},
        //! If true, show button when value has been selected
        button: Boolean,
        //! If true, value must come from a selection
        mustExist: {type: Boolean, default: false},
        //! Minimum input size before fetching
        minFetchLength: {type: Number, default: 3},
        modelValue: {default: ''},
    },

    data() {
        return {
            inputValue: this.modelValue || '',
            query: '',
            items: [],
            selectedIndex: -1,
            cursor: -1,
            promise: null,
        }
    },

    watch: {
        modelValue(value) {
            this.inputValue = value
        },

        inputValue(value) {
            if(value != this.inputValue && value != this.modelValue)
                this.$emit('update:modelValue', value)
        },
    },

    computed: {
        isFetching() { return !!this.promise },

        selected() {
            let index = this.selectedIndex
            if(index<0)
                return null
            index = Math.min(index, this.items.length-1)
            return this.items[index]
        },

        selectedValue() {
            let value = this.itemValue(this.selected)
            if(!value && !this.mustExist)
                value = this.inputValue
            return value
        },

        selectedLabel() {
            return this.itemLabel(this.selected)
        },

        dropdownClass() {
            var active = this.cursor > -1 && this.items.length;
            if(active && this.items.length == 1 &&
                    this.itemValue(this.items[0]) == this.inputValue)
                active = false
            return ['dropdown is-fullwidth', active ? 'is-active':'']
        },
    },

    methods: {
        itemValue(item) {
            return this.valueField ? item && item[this.valueField] : item;
        },

        itemLabel(item) {
            return this.labelField ? item && item[this.labelField] : item;
        },

        hide() {
            this.cursor = -1;
            this.selectedIndex = -1;
        },

        move(index=-1, relative=false) {
            if(relative)
                index += this.cursor
            this.cursor = Math.max(-1, Math.min(index, this.items.length-1))
        },

        select(index=-1, relative=false, active=null) {
            if(relative)
                index += this.selectedIndex
            else if(index == this.selectedIndex)
                return

            this.selectedIndex = Math.max(-1, Math.min(index, this.items.length-1))
            if(index >= 0) {
                this.inputValue = this.selectedLabel
                this.$refs.input.focus()
            }
            if(this.selectedIndex < 0)
                this.$emit('unselect')
            else
                this.$emit('select', index, this.selected, this.selectedValue)

            if(active!==null)
                active && this.move(0) || this.move(-1)
        },

        onInputFocus() {
            this.cursor < 0 && this.move(0)
        },

        onBlur(event) {
            var index = event.relatedTarget && event.relatedTarget.dataset.autocompleteIndex;
            if(index !== undefined)
                this.select(index, false, false)
            this.cursor = -1;
        },

        onKeyDown(event) {
            if(event.ctrlKey || event.altKey || event.metaKey)
                return
            switch(event.keyCode) {
                case 13: this.select(this.cursor, false, false)
                         break
                case 27: this.hide(); this.select()
                         break
                case 38: this.move(-1, true)
                         break
                case 40: this.move(1, true)
                         break
                default: return
            }
            event.preventDefault()
            event.stopPropagation()
        },

        onKeyUp(event) {
            if(event.ctrlKey || event.altKey || event.metaKey)
                return

            const value = event.target.value
            if(value === this.query)
                return

            this.inputValue = value;
            if(!value)
                return this.selected && this.select(-1)
            if(!this.minFetchLength || value.length >= this.minFetchLength)
                this.fetch(value)
        },

        fetch(query) {
            if(!query || this.promise)
                return

            this.query = query
            var url = this.url.replace('${query}', query)
            var promise = this.model ? this.model.fetch(url, {many:true})
                                     : fetch(url, Model.getOptions()).then(d => d.json())

            promise = promise.then(items => {
                this.items = items || []
                this.promise = null;
                this.move(0)
                return items
            }, data => {this.promise = null; Promise.reject(data)})
            this.promise = promise
            return promise
        },
    },

    mounted() {
        const form = this.$el.closest('form')
        form.addEventListener('reset', () => {
            this.inputValue = this.value;
            this.select(-1)
        })
    }
}

</script>
