<template>
    <div class="my-1">
        <label class="col-form-label" for="countrySelect">{{
            $t("country")
        }}</label>
        <VueMultiselect
            id="countrySelect"
            label="name"
            track-by="id"
            :custom-label="transName"
            :placeholder="$t('select_country')"
            :options="sortedCountries"
            v-model="value"
            :select-label="$t('multiselect.select_label')"
            :deselect-label="$t('multiselect.deselect_label')"
            :selected-label="$t('multiselect.selected_label')"
            @select="selectCountry"
            @remove="remove"
        />
    </div>
</template>

<script>
import VueMultiselect from "vue-multiselect";

export default {
    name: "CountrySelection",
    components: { VueMultiselect },
    props: ["context", "entity", "flag", "checkErrors"],
    emits: ["getCities"],
    data() {
        return {
            value: this.selectCountryByCode(
                this.context.edit
                    ? this.entity.selected.country.code
                    : this.context.defaults.default_country,
            ),
        };
    },
    computed: {
        sortedCountries() {
            const countries = this.entity.loaded.countries;
            let sortedCountries = [];
            sortedCountries.push(
                ...countries.filter((c) => c.countryCode === "FR"),
            );
            sortedCountries.push(
                ...countries.filter((c) => c.countryCode === "BE"),
            );
            sortedCountries.push(
                ...countries
                    .filter((c) => c.countryCode !== "FR")
                    .filter((c) => c.countryCode !== "BE"),
            );
            return sortedCountries;
        },
    },
    mounted() {
        console.log("country selection mounted", this.value);
        if (this.value !== undefined) {
            this.selectCountry(this.value);
        }
    },
    methods: {
        selectCountryByCode(countryCode) {
            return this.entity.loaded.countries.filter(
                (c) => c.countryCode === countryCode,
            )[0];
        },
        transName({ name }) {
            return name.fr; //TODO multilang
        },
        selectCountry(value) {
            //console.log('select country', value);
            this.entity.selected.country = value;
            this.$emit("getCities", value);
            this.checkErrors();
        },
        remove() {
            this.entity.selected.country = null;
            this.checkErrors();
        },
    },
};
</script>

<style src="vue-multiselect/dist/vue-multiselect.css"></style>
