<template>
    <ul class="list-suggest remove-items" v-if="picked.length">
        <li v-for="p in picked" @click="removeEntity(p)" :key="p.type+p.id">
            <span class="chill_denomination">{{ p.text }}</span>
        </li>
    </ul>
    <ul class="record_actions">
        <li class="add-persons">
            <add-persons
                :options="addPersonsOptions"
                :key="uniqid"
                :buttonTitle="translatedListOfTypes"
                :modalTitle="translatedListOfTypes"
                ref="addPersons"
                @addNewPersons="addNewEntity"
            >
            </add-persons>
        </li>
    </ul>
</template>

<script>
import AddPersons from "ChillPersonAssets/vuejs/_components/AddPersons.vue";
import { appMessages } from "./i18n";

export default {
    name: "PickEntity",
    props: {
        multiple: {
            type: Boolean,
            required: true,
        },
        types: {
            type: Array,
            required: true,
        },
        picked: {
            required: true,
        },
        uniqid: {
            type: String,
            required: true,
        }
    },
    emits: ['addNewEntity', 'removeEntity'],
    components: {
        AddPersons,
    },
    data() {
        return {
            key: ''
        };
    },
    computed: {
        addPersonsOptions() {
            return {
                uniq: !this.multiple,
                type: this.types,
                priority: null,
                button: {
                    size: 'btn-sm',
                    class: 'btn-submit',
                },
            };
        },
        translatedListOfTypes() {
            let trans = [];
            this.types.forEach(t => {
                if (this.$props.multiple) {
                    trans.push(appMessages.fr.pick_entity[t].toLowerCase());
                } else {
                    trans.push(appMessages.fr.pick_entity[t + '_one'].toLowerCase());
                }
            })

            if (this.$props.multiple) {
                return appMessages.fr.pick_entity.modal_title + trans.join(', ');
            } else {
                return appMessages.fr.pick_entity.modal_title_one + trans.join(', ');
            }
        }
    },
    methods: {
        addNewEntity({ selected, modal }) {
            selected.forEach((item) => {
                    this.$emit('addNewEntity', item.result);
                }, this
            );
            this.$refs.addPersons.resetSearch(); // to cast child method
            modal.showModal = false;
        },
        removeEntity(entity) {
            this.$emit('removeEntity', entity);
        }
    },
}
</script>
