import { __awaiter, __decorate, __extends, __generator } from "tslib";
import { getExampleNumber, parseNumber } from 'libphonenumber-js';
import Component from 'vue-class-component';
import { Emit, Model, Prop, Ref, Watch } from 'vue-property-decorator';
import { InputLabel } from '../../mixins/input-label/input-label';
import { InputManagement } from '../../mixins/input-management/input-management';
import { InputState } from '../../mixins/input-state/input-state';
import { InputMaxWidth, InputMaxWidthValues, InputWidth } from '../../mixins/input-width/input-width';
import { allCountriesOptionsEn } from '../../utils/country/countries-options-en';
import { allCountriesOptionsFr } from '../../utils/country/countries-options-fr';
import { MCountryCodeISO2 } from '../../utils/country/country';
import { FRENCH } from '../../utils/i18n/i18n';
import uuid from '../../utils/uuid/uuid';
import { ModulVue } from '../../utils/vue/vue';
import { MInputMask } from '../input-mask/input-mask';
import { MInputStyle } from '../input-style/input-style';
import { MSelectVirtualScroll } from '../select-virtual-scroll/select-virtual-scroll';
import { MSelectItem } from '../select/select-item/select-item';
import { MValidationMessage } from '../validation-message/validation-message';
import { CustomAsYouType } from './formatter/custom-asyoutype';
import WithRender from './phonefield.html?style=./phonefield.scss';
window.Cleave = window.Cleave || {};
window.Cleave.AsYouTypeFormatter = CustomAsYouType;
var MPhonefield = /** @class */ (function (_super) {
    __extends(MPhonefield, _super);
    function MPhonefield() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.validationMessageId = uuid.generate();
        _this.valueDropdownCountryId = uuid.generate();
        _this.examples = require('libphonenumber-js/examples.mobile.json');
        _this.countryModelInternal = MCountryCodeISO2.Empty;
        _this.internalCountry = { name: '', iso2: MCountryCodeISO2.Empty, dialCode: '' };
        _this.selectedCountries = _this.$i18n.currentLang() === FRENCH ? allCountriesOptionsFr : allCountriesOptionsEn;
        _this.countries = _this.selectedCountries.sort(function (a, b) { return (_this.nameNormalize(a.name) > _this.nameNormalize(b.name)) ? 1 : ((_this.nameNormalize(b.name) > _this.nameNormalize(a.name)) ? -1 : 0); });
        _this.i18nInternalLabel = _this.$i18n.translate('m-phonefield:phone-label');
        _this.i18nCountryLabel = _this.$i18n.translate('m-phonefield:country-label');
        _this.i18nExample = _this.$i18n.translate('m-phonefield:example');
        return _this;
    }
    MPhonefield.prototype.beforeMount = function () {
        // sprites-flags.svg is a very big file, this is why sprites should only be added to the DOM before this component is mounted.
        var sprites = require('../../assets/icons/sprites-flags.svg');
        var svg = this.$svg;
        if (this.externalSprite) {
            if (!svg.isInExternalSprites('mflag')) {
                svg.addExternalSprites(sprites, 'mflag');
            }
        }
        else {
            this.internalSpriteId = svg.addInternalSprites(sprites);
        }
    };
    MPhonefield.prototype.destroyed = function () {
        if (this.internalSpriteId) {
            this.$svg.removeInternalSprite(this.internalSpriteId);
        }
    };
    MPhonefield.prototype.emitNewValue = function (_newValue) { };
    MPhonefield.prototype.emitContrySelected = function (country) { };
    MPhonefield.prototype.onContryChange = function (country) {
        var _this = this;
        if (country.iso) {
            this.countryModelInternal = country.iso;
            this.internalCountry = this.countries.find(function (country) { return country.iso2 === _this.countryModelInternal; });
            if (!this.as().internalValue) {
                this.as().internalValue = '+' + this.internalCountry.dialCode;
            }
        }
    };
    MPhonefield.prototype.onValueChanged = function (value) {
        if (value) {
            this.parsePhoneNumber(value);
        }
    };
    MPhonefield.prototype.spriteId = function (iso) {
        var svg = this.$svg;
        var spriteId = "mflag-svg__flag-" + iso;
        if (document.getElementById(spriteId)) {
            return "#" + spriteId;
        }
        else if (svg && svg.getExternalSpritesFromSpriteId(spriteId)) {
            return svg.getExternalSpritesFromSpriteId(spriteId);
        }
        else if (iso) {
            this.$log.warn("\"" + iso + "\" is not a valid iso country. Make sure that the sprite has been loaded via the $svg instance service.");
        }
    };
    MPhonefield.prototype.isLastPriorityIsoCountrie = function (iso) {
        return this.priorityIsoCountries[this.priorityIsoCountries.length - 1] === iso;
    };
    Object.defineProperty(MPhonefield.prototype, "isoCountries", {
        get: function () {
            return this.countriesSorted.map(function (contry) { return contry.iso2; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "listMinWidth", {
        get: function () {
            switch (this.as().maxWidth) {
                case InputMaxWidth.Medium:
                case InputMaxWidth.Large:
                    return InputMaxWidthValues.Medium;
                case InputMaxWidth.None:
                case InputMaxWidth.XSmall:
                case InputMaxWidth.Small:
                case InputMaxWidth.Regular:
                    return InputMaxWidthValues.Regular;
                default:
                    return this.as().maxWidth;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "countriesSorted", {
        get: function () {
            var _this = this;
            var finalCountriesList = [];
            this.priorityIsoCountries.forEach(function (isoPriorityCountry) {
                var currentCountry = _this.countries.find(function (isoCountry) { return isoCountry.iso2 === isoPriorityCountry; });
                if (currentCountry) {
                    finalCountriesList.push(currentCountry);
                }
            });
            this.countries.filter(function (country) {
                if (!_this.priorityIsoCountries.includes(country.iso2)) {
                    finalCountriesList.push(country);
                }
            });
            return finalCountriesList;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "propLabel", {
        get: function () {
            return this.label ? this.label : this.i18nInternalLabel;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "hasPhonefieldError", {
        get: function () {
            return this.as().hasError;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "isPhonefieldValid", {
        get: function () {
            return this.as().isValid;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "inputMaskOptions", {
        get: function () {
            return {
                phone: true,
                phoneRegionCode: this.phoneRegionCode,
                prefix: this.prefix
            };
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "phoneRegionCode", {
        get: function () {
            return this.internalCountry ? this.internalCountry.iso2.toUpperCase() : '';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "prefix", {
        get: function () {
            return '+' + this.internalCountry.dialCode;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "example", {
        get: function () {
            var phoneNumber = getExampleNumber(this.phoneRegionCode, this.examples);
            return phoneNumber ? phoneNumber.formatInternational() : '';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MPhonefield.prototype, "countryModel", {
        get: function () {
            return this.countryModelInternal;
        },
        set: function (value) {
            this.internalCountry = this.countries.find(function (country) { return country.iso2 === value; });
            this.as().internalValue = '+' + this.internalCountry.dialCode;
            this.countryModelInternal = value;
        },
        enumerable: false,
        configurable: true
    });
    MPhonefield.prototype.inputChanged = function (value) {
        this.emitNewValue(value);
    };
    MPhonefield.prototype.parsePhoneNumber = function (value) {
        var _this = this;
        var parsedNumber = parseNumber(value, { extended: true });
        if (parsedNumber.country && parsedNumber.valid) {
            this.countryModelInternal = parsedNumber.country.toLowerCase();
            this.internalCountry = this.countries.find(function (country) { return country.iso2 === _this.countryModelInternal; });
            this.emitContrySelected({
                iso: this.internalCountry.iso2,
                prefix: this.internalCountry.dialCode
            });
        }
    };
    MPhonefield.prototype.nameNormalize = function (name) {
        return name.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
    };
    MPhonefield.prototype.onContryChanged = function (countryIso, _index, _$event) {
        this.countryModel = countryIso;
        this.emitContrySelected({
            iso: this.internalCountry.iso2,
            prefix: this.internalCountry.dialCode
        });
    };
    MPhonefield.prototype.focusInputSelect = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.$nextTick()];
                    case 1:
                        _a.sent();
                        if (!this.refInputSelect) {
                            return [2 /*return*/];
                        }
                        this.refInputSelect.focus();
                        return [2 /*return*/];
                }
            });
        });
    };
    MPhonefield.prototype.focusInput = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.$nextTick()];
                    case 1:
                        _a.sent();
                        if (!this.refInputMask) {
                            return [2 /*return*/];
                        }
                        this.refInputMask.focus();
                        return [2 /*return*/];
                }
            });
        });
    };
    __decorate([
        Prop(),
        Model('input')
    ], MPhonefield.prototype, "value", void 0);
    __decorate([
        Prop()
    ], MPhonefield.prototype, "label", void 0);
    __decorate([
        Prop({
            default: function () { return ({
                iso: MCountryCodeISO2.Canada,
                prefix: '1'
            }); }
        })
    ], MPhonefield.prototype, "country", void 0);
    __decorate([
        Prop({
            default: function () { return [MCountryCodeISO2.Canada]; }
        })
    ], MPhonefield.prototype, "priorityIsoCountries", void 0);
    __decorate([
        Prop({
            default: false
        })
    ], MPhonefield.prototype, "externalSprite", void 0);
    __decorate([
        Prop({ default: function () { return "mPhonefield-" + uuid.generate(); } })
    ], MPhonefield.prototype, "id", void 0);
    __decorate([
        Ref('inputMask')
    ], MPhonefield.prototype, "refInputMask", void 0);
    __decorate([
        Ref('inputSelect')
    ], MPhonefield.prototype, "refInputSelect", void 0);
    __decorate([
        Emit('input')
    ], MPhonefield.prototype, "emitNewValue", null);
    __decorate([
        Emit('update:country')
    ], MPhonefield.prototype, "emitContrySelected", null);
    __decorate([
        Watch('country', { immediate: true })
    ], MPhonefield.prototype, "onContryChange", null);
    __decorate([
        Watch('value', { immediate: true })
    ], MPhonefield.prototype, "onValueChanged", null);
    MPhonefield = __decorate([
        WithRender,
        Component({
            modul: {
                i18n: {
                    'fr': require('./phonefield.lang.fr.json'),
                    'en': require('./phonefield.lang.en.json')
                }
            },
            mixins: [
                InputState,
                InputWidth,
                InputLabel,
                InputManagement
            ],
            components: {
                MInputStyle: MInputStyle,
                MInputMask: MInputMask,
                MSelectVirtualScroll: MSelectVirtualScroll,
                MSelectItem: MSelectItem,
                MValidationMessage: MValidationMessage
            }
        })
    ], MPhonefield);
    return MPhonefield;
}(ModulVue));
export { MPhonefield };
export { MCountryCodeISO2 } from '../../utils/country/country';
//# sourceMappingURL=phonefield.js.map