<template>
    <badge-select-field :value="this.value" :options="this.tags" @addElement="addTag" ref="badgeSelect">
        <template v-slot:default="{option, index}">
            <span class="badge bg-dark" @click="removeTag(index)">
                {{ getNameFromHandle(option) }}
            </span>
        </template>
    </badge-select-field>
</template>

<style scoped>
.badge {
    padding: .3rem .5rem;
}

.badge:hover {
    background-color: var(--bs-danger) !important;
}
</style>

<script>
import * as BIcons from "bootstrap-icons-vue";
import {mapActions, mapState, mapGetters} from "vuex";
//import BadgeSelectField from "@/../extras/components/inputs/BadgeSelectField.vue";
import BadgeSelectField from "@/components/inputs/BadgeSelectField.vue";

export default {
    name: "TagField",
    components: {
        BadgeSelectField,
        ...BIcons
    },
    props: {
        value: {
            type: Array,
            required: true
        }
    },
    model: {
        prop: "value",
        event: "input"
    },
    computed: {
        ...mapState(["tags"]),
        ...mapGetters(["getNameFromHandle"]),
        availableTags() {
            return this.tags.filter(tag => !this.localValue.includes(tag));
        },
        localValue: {
            get() {
                return this.value;
            },
            set(value) {
                this.$emit("input", value);
            }
        }
    },
    methods: {
        ...mapActions(["fetchTags"]),
        addTag(tag) {
            if (this.localValue.includes(tag)) {
                this.localValue.splice(this.localValue.indexOf(tag), 1);
                this.$refs.badgeSelect.resetSelection();
            } else if (this.availableTags.includes(tag)) {
                this.localValue.push(tag);
                this.$refs.badgeSelect.resetSelection();
            }else{
                // input does not match any tag
            }
        },
        removeTag(index) {
            this.localValue.splice(index, 1);
        }
    },
    mounted() {
        this.fetchTags();
    }
}
</script>