<template>
    <div>
        <badge-select-field :value="this.splicedValue" :options="this.properties.map(p => p.name)" @addElement="addProperty"
                            ref="badgeSelect">
            <template v-slot:default="{option, index}">
                <PropertyBadge :key="index"
                               :property="option"
                               @modelChange="setValue(index, $event)"
                               @remove="removeProperty(index)"/>
            </template>
        </badge-select-field>
    </div>
</template>

<style scoped>
</style>

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

export default {
    name: "PropertyField",
    components: {
        BadgeSelectField,
        PropertyBadge,
        ...BIcons
    },
    props: {
        value: {
            type: Array,
            required: true
        }
    },
    model: {
        prop: "value",
        event: "input"
    },
    computed: {
        ...mapState(["properties"]),
        availableProperties() {
            if (!this.properties) return [];
            if (!this.value) return this.properties;
            return this.properties.filter(property => !this.value.map(p => p.name).includes(property.name));
        },
        localValue: {
            get() {
                if (!this.value) return [];
                return this.value;
            },
            set(value) {
                this.$emit("input", value);
            }
        },
        splicedValue() {
            if (!this.value || !this.properties) return [];
            return this.value.map(property => {
                return {
                    ...this.properties.find(p => p.name === property.name),
                    value: property.value
                }
            })
        }
    },
    methods: {
        ...mapActions(["fetchProperties"]),
        addProperty(property) {
            if (property !== "") {
                this.localValue.push({name: property, value: 0});
                this.property = "";
            }
        },
        removeProperty(index) {
            this.localValue.splice(index, 1);
        },
        setValue(index, value) {
            if (value.target)
                return;
            this.localValue[index] = value;
            return true;
        }
    },
    mounted() {
        this.fetchProperties();
    }
}
</script>