<template>
    <div>
        <div v-show="tags.length === 0" class="alert alert-info">Pas de mot-clé pour le moment.</div>
        <div class="tag-list">
            <tag-list-item ref="items"
                class="tag-list-item"
                v-for="(tag, index) in tags"
                v-show="tags.length > 0"
                v-bind:label="tag.tag_label"
                v-bind:index="index"
                v-bind:accuracy="tag.accuracy"
                v-bind:relevancy="tag.relevancy"
                v-bind:readonly="readonly"></tag-list-item>
        </div>
        <typeahead ref="typeahead" placeholder="Ajouter un mot-clé" v-show="!readonly"></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 []; }
            },
            readonly: {
                type: Boolean,
                default: false
            },
        },
        data() {
            return {
                tags: _.cloneDeep(this.originalTags)
            }
        },
        components: {
            "typeahead": Typeahead,
            "tag-list-item": TagListItem
        },
        watch: {
            originalTags: function(originalTags) {
                this.tags = _.cloneDeep(this.originalTags);
                this.hideAll();
            },
            tags: function(tags) {
                this.$emit('change', { tags: tags });
            },
            readonly: function(readonly) {
                if (readonly) {
                    this.hideAll();
                }
            }
        },
        mounted() {
            this.$refs.typeahead.$on('selected', (tag) => {
                this.tags.push(tag);
            });
        },

        methods: {
            hideAll: function() {
                if (!this.$refs.items) { return; }
                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>

.alert {
    padding: 10px;
    font-size: 12px;
}

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

.tag-list-item:first-of-type {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
}

.tag-list-item:last-of-type {
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
}

</style>
