<template>
    <div class="input-group" dir="ltr">
        <input type="hidden"
               :value="cc"
               :name="countryCodeInputName" />
        <div class="input-group-prepend">
            <j-country-select v-model="cc"
                              :disabled="disabled"
                              :display-field="countryDisplayField"
                              :variant="variant"
                              :size="size"></j-country-select>
        </div>
        <input class="form-control h-auto px-1 py-0"
               type="text"
               v-model="ph"
               dir="ltr"
               :name="inputName"
               :disabled="disabled"
               ref="input">
    </div>
</template>

<script>
export default {
    props: {
        value: {
            type: Object,
            default() {
                return {
                    phone: '',
                    countryCode: 'US'
                };
            }
        },
        disabled: {
            type: Boolean,
            default: false
        },
        inputName: {
            type: String,
            default: ''
        },
        countryCodeInputName: {
            type: String,
            default: ''
        },
        variant: {
            type: String,
            default: 'primary'
        },
        size: {
            type: String,
            default: null       // null or sm or lg
        },
        countryDisplayField: {
            type: String,
            default: 'name'     // 'code' or 'name'
        }
    },
    data() {
        return {
            cc: this.value.countryCode,
            ph: this.value.phone
        };
    },
    methods: {
        focus() {
            this.$refs.input.focus();
        }
    },
    watch: {
        cc() {
            var k = {
                countryCode: this.cc,
                phone: this.ph
            };
            this.$emit('input', k);
        },
        ph() {
            var k = {
                countryCode: this.cc,
                phone: this.ph
            };
            this.$emit('input', k);
        },
        value: {
            handler() {
                this.cc = this.value.countryCode;
                this.ph = this.value.phone;
            },
            deep: true
        }
    }
}
</script>