(function () {
    function PawAion() {
        this.settings = {
            id: 'aion_app',
            guide: 'WEB',
            language: null,
            url: null
        };
        this.isUser = false;
        this.isInit = false;
    }

    PawAion.prototype.init = function (settings, isUser) {
        if (this.isInit) {
            return;
        }
        var self = this;
        this.settings = paw.lang.append(this.settings, settings || {});
        this.isUser = isUser;

        if (paw.utils.value.notSet(this.settings.url) || (paw.utils.value.isString(this.settings.url) && this.settings.url.length === 0)) {
            return paw.utils.async.promise();
        }

        var p = this.isUser ? this.fetchEncParameter() : paw.utils.async.promise();
        return p.then(function (enc) {
            self.initAionScript(enc);
            self.initLauncher();
            self.isInit = true;
        });
    };

    PawAion.prototype.initLauncher = function () {
        var $aionLauncherAction = $('#aion-launcher-action');
        if ($aionLauncherAction.length > 0) {
            $aionLauncherAction.click(function () {
                $('#app .aion-app .chat-bot-launcher').click();
            });
        }
    };

    PawAion.prototype.initAionScript = function (enc) {
        var script = document.createElement('script');
        this.setScriptAttr(script, 'id', this.settings.id);
        this.setScriptAttr(script, 'type', 'module');
        this.setScriptAttr(script, 'src', this.settings.url);
        this.setScriptAttr(script, 'data-guide', this.settings.guide);
        this.setScriptAttr(script, 'data-language', this.settings.language);
        this.setScriptAttr(script, 'data-enc', enc);
        document.head.appendChild(script);
    };

    PawAion.prototype.setScriptAttr = function (script, attr, value) {
        if (paw.utils.value.isSet(value) || (paw.utils.value.isString(value) && value.length > 0)) {
            script.setAttribute(attr, value);
        }
    };
        
    PawAion.prototype.fetchEncParameter = function () {
        var d = paw.utils.async.defer();
        $.ajax({
            method: 'GET',
            url: '/Aion/GetEncParameter',
            success: function (enc) {
                d.resolve(enc);
            },
            error: function () {
                d.reject();
            }
        })
        return d.promise;
    };

    paw.mod.Aion = new PawAion();
})(paw);