<template>
    <j-autocomplete :get-id="o => o === undefined || o === null ? null : o.code"
                    :options="countries"
                    :id="value"
                    @change="id => $emit('input', id)"
                    v-model="country"
                    :search-properties="['code', 'name']"
                    :placeholder="placeholder"
                    :delay="delay"
                    :clearable="clearable"
                    :disabled="disabled"
                    :variant="variant"
                    :size="size">
        <span slot="result"
              slot-scope="{option, id}">
            <img :src="getFlag(id)"
                 style="width: 32px; height: 32px;" />
            &nbsp;
            <span>{{getFullName(option)}}</span>
        </span>
        <span slot="option"
              slot-scope="{option, id}">
            <img :src="getFlag(id)"
                 style="width: 32px; height: 32px;" />
            &nbsp;
            <span>{{getFullName(option)}}</span>
        </span>
    </j-autocomplete>
</template>

<script>
import { removeEnding, getCountries } from "./util";
import { countryHelper } from "libj-core";
export default {
    props: {
        value: {
            type: String,
            default: ''
        },
        displayField: {
            default: null
        },
        placeholder: {
            type: String,
            default: null
        },
        delay: {
            type: Number,
            default: 500
        },
        clearable: {
            type: Boolean,
            default: false
        },
        disabled: {
            type: Boolean,
            default: false
        },
        variant: {
            type: String,
            default: 'primary'
        },
        size: {
            type: String,
            default: null       // null or sm or lg
        },
    },
    data() {
        return {
            country: {},
            countries: getCountries()
        };
    },
    mounted() {
        this.update();
    },
    methods: {
        getFullName(country) {
            if (country === undefined || country === null) {
                return '';
            }
            if (this.displayField === undefined || this.displayField === null) {
                return `${country.code} - ${country.name}`;
            }
            return country[this.displayField];
        },
        getFlag(code) {
            if (code === undefined || code === null || code.length === 0) {
                return '';
            }
            return `${removeEnding(countryHelper.getFlagsPath(), '/')}/${code.toUpperCase()}.svg`;
        },
        update() {
            var c = this.countries.find(a => a.code === this.value);
            this.country = Object.assign({}, c);
        }
    },
    watch: {
        value() {
            this.update();
        },
    }
}
</script>