import BaseModal from "./BaseModal";
class ModalAddLanguage extends BaseModal {
    
    _currentSelection = {
        name: '',
        image: '',
        code: ''
    };

    constructor(id, options = {}) {
        super(id, options);
        this.initSelect2();
        this._registerEvents();
    }

    _registerEvents() {
        const _this = this;
        this._ui.find('.skl-save-btn').on('click', function(event) {
            event.preventDefault();
            const saveCallback = _this._options?.saveCallback;
            if (saveCallback instanceof Function) {
                saveCallback(_this._currentSelection);
                _this._modal.hide();
            }
        })

        jQuery('#select-language').on('change', function() {
            _this._populate();
        });
    }

    initSelect2() {
        jQuery("#select-language").select2({
            templateResult: function (option) {
                if (!option.id) return option.text; // Default
                const imageUrl = jQuery(option.element).data('image');
                return jQuery(
                    '<span><img src="' +
                    imageUrl +
                    '" style="width:20px;margin-right:10px;">' +
                    option.text +
                    "</span>"
                );
            },
            templateSelection: function (option) {
                if (!option.id) return option.text; // Default
                const imageUrl = jQuery(option.element).data('image');
                return jQuery(
                    '<span><img src="' +
                    imageUrl +
                    '" style="width:20px;margin-right:10px;">' +
                    option.text +
                    "</span>"
                );
            },
        });
    }

    open(openOptions) {
        super.open(openOptions);
        const { countryCode } = this._openOptions;
        if (countryCode && typeof countryCode === 'string' && countryCode !== '') {
            jQuery('#select-language').val(countryCode).trigger('change');
        } else {
            jQuery('#select-language').val('').trigger('change');
        }
        this._populate();
    }

    _populate() {
        const code = jQuery('#select-language').val();
        const name = jQuery("#select-language option:selected").data('name');
        const image = jQuery("#select-language option:selected").data('image');
        this._currentSelection = {
            code, name, image, ...this._openOptions
        }
        this._validate();
    }

    _validate() {
        const { code } = this._currentSelection;
        if (code !== '') {
            this._ui.find('.skl-save-btn').removeAttr('disabled');
        } else {
            this._ui.find('.skl-save-btn').attr('disabled', true);
        }
    }
}
export default ModalAddLanguage;
