<template>
    <div :class="['auto-complete', open ? 'open' : 'closed']">

        <div class="input-group">

            <div class="input-group-addon">
                <i class="material-icons">search</i>
            </div>

            <input class="form-control input-lg"
                   placeholder="Type in to Search..."
                   type="text"
                   name="search_query"
                   v-model="query"
                   @keyup="search"
                   @keydown.enter='enter'
                   @keydown.down='down'
                   @keydown.up='up'
                   debounce="500"
                   autocomplete="off"
            />
        </div>

        <ul class="dropdown-menu">
            <li v-for="(result, index) in results"
                :class="{'active': isActive(index)}"
                @click="resultClick(index)"
            >
                <a :href="'/task/' + result.id">
                    {{ result.title }}
                    {{ result.status }}
                </a>
            </li>
        </ul>

    </div>
</template>


<script>
export default {
    props : {
        url : {
            type : String,
            required : true
        }
    },
    data() {
        return {
            open : false,
            current : 0,
            query : '',
            results : '',
            errors : []
        }
    },
    methods : {
        search(e) {
            if (this.query.length < 3) return;

            switch (e.keyCode) {
                case 37: // left
                case 38: // up
                case 39: // right
                case 40: // down
                    return;
            }

            window.axios.get('/search/' + this.query)
                .then((response) => {
                    this.results = response.data;
                    this.open = true;
                    console.log(this.results);
                })
                .catch(e => {
                    this.errors.push(e)
                });
        },
        enter() {
            this.query = this.results[this.current];
            this.open = false;
        },
        up() {
            if (this.current > 0)
                this.current--;
        },
        down() {
            if (this.current < this.results.length - 1)
                this.current++;
        },
        isActive(index) {
            return index === this.current;
        },
        resultClick(index) {
            this.query = this.results[index].title;
            this.open = false;
        }
    }
}
</script>
