<template>
  <div class="my-1">
    <label class="col-form-label" for="countrySelect">{{
      trans(ADDRESS_COUNTRY)
    }}</label>
    <VueMultiselect
      id="countrySelect"
      label="name"
      track-by="id"
      :custom-label="transName"
      :placeholder="trans(ADDRESS_SELECT_COUNTRY)"
      :options="sortedCountries"
      v-model="value"
      :select-label="trans(MULTISELECT_SELECT_LABEL)"
      :deselect-label="trans(MULTISELECT_DESELECT_LABEL)"
      :selected-label="trans(MULTISELECT_SELECTED_LABEL)"
      @select="selectCountry"
      @remove="remove"
    />
  </div>
</template>

<script>
import VueMultiselect from "vue-multiselect";
import { localizeString } from "ChillMainAssets/lib/localizationHelper/localizationHelper";
import {
  MULTISELECT_SELECTED_LABEL,
  MULTISELECT_SELECT_LABEL,
  MULTISELECT_DESELECT_LABEL,
  ADDRESS_COUNTRY,
  ADDRESS_SELECT_COUNTRY,
  trans,
} from "translator";

export default {
  name: "CountrySelection",
  components: { VueMultiselect },
  setup() {
    return {
      MULTISELECT_SELECTED_LABEL,
      MULTISELECT_SELECT_LABEL,
      MULTISELECT_DESELECT_LABEL,
      ADDRESS_COUNTRY,
      ADDRESS_SELECT_COUNTRY,
      trans,
    };
  },
  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 localizeString(name);
    },
    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>
