<template>
    <div>
        <div class="tag-list">
            <tag-list-item ref="items"
                v-for="(tag, index) in tags"
                v-if="tags.length > 0"
                v-bind:label="tag.tag_label"
                v-bind:index="index"
                v-bind:accuracy="tag.accuracy"
                v-bind:relevancy="tag.relevancy"></tag-list-item>
        </div>
        <typeahead ref="typeahead" placeholder="Rechercher"></typeahead>
    </div>
</template>

<script>

    import TagListItem from './TagListItem.vue'
    import Typeahead from './Typeahead.vue'
    import _ from 'lodash'

    export default {
        props: {
            originalTags: {
                type: Array,
                default: function () {
                    return [];
                }
            },
        },
        data() {
            return {
                tags: _.cloneDeep(this.originalTags)
            }
        },
        components: {
            "typeahead": Typeahead,
            "tag-list-item": TagListItem
        },
        watch: {
            originalTags: function(originalTags) {
                this.tags = _.cloneDeep(this.originalTags);
            },
            tags: function(tags) {
                this.$emit('change', { tags: tags });
            }
        },
        mounted() {
            this.$refs.typeahead.$on('selected', (tag) => {
                this.tags.push(tag);
            });
        },

        methods: {
            hideAll: function() {
                this.$refs.items.forEach((item) => item.hide());
            },
            replaceItemAt: function(index, data) {
                const tag = this.tags[index];
                Object.assign(tag, data);
                this.tags.splice(index, 1, tag);
            },
            removeItemAt: function(index) {
                this.tags.$remove(this.tags[index]);
            }
        }

    }

</script>

<style scoped>

.tag-list {
    margin-bottom: 15px;
}

</style>
