"use strict";
cc._RF.push(module, '88396uYlDlKdpiCzSL5nr8D', 'CCMBinding');
// lib/CCMBinding/CCMBinding.ts

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var AUTO_INCREASE_ID = 0;
var ERROR_CODE_METHOD_NOT_DEFINED = -1;
var ERROR_CODE_PARAMS_ERROR = -2;
var ERROR_CODE_TIMEOUT = -3;
var ERROR_CODE_UNKNOW = -999;
var CCMBinding = /** @class */ (function () {
    function CCMBinding() {
        this.DEFAULT_OPTIONS = { timeout: 60, hasCallback: true, onProgress: undefined };
        this._options = this.DEFAULT_OPTIONS;
    }
    Object.defineProperty(CCMBinding, "Instance", {
        get: function () {
            if (!this.instance) {
                this.instance = new CCMBinding();
            }
            return this.instance;
        },
        enumerable: false,
        configurable: true
    });
    CCMBinding.withOptions = function (options) {
        return this.Instance.withOptions(options);
    };
    CCMBinding.callNativeMethod = function (methodName, args) {
        return this.Instance.callNativeMethod(methodName, args);
    };
    /**
     * 创建一个临时请求native方法的可选项，包含：
     * 超时时间设置默认60秒，过程回调（若有)
     * @param options Options,
     */
    CCMBinding.prototype.withOptions = function (options) {
        var oriProto = Object.getPrototypeOf(this);
        var temp = Object.assign(Object.create(oriProto), this);
        temp._options = Object.assign({}, this.DEFAULT_OPTIONS, options);
        return temp;
    };
    CCMBinding.prototype.callNativeMethod = function (methodName, args) {
        var _this = this;
        console.log("options:" + JSON.stringify(this._options) + ", args:" + args);
        var hasCallback = this._options.hasCallback;
        var hasProgress = this._options.onProgress;
        return new Promise(function (resolve, reject) {
            var cbName = '';
            var timeoutId;
            var cbProgressName = '';
            if (hasCallback || hasProgress) {
                // eslint-disable-next-line no-plusplus
                cbName = "CCM_CB" + new Date().getTime() + "_" + AUTO_INCREASE_ID++;
                cbProgressName = cbName + "_p";
                timeoutId = setTimeout(function () {
                    if (window[cbName]) {
                        _this.clearCallback(cbName, -1, cbProgressName);
                        reject({ code: ERROR_CODE_TIMEOUT, msg: "delete cb name: " + cbName + ",because of timeout" });
                    }
                }, _this._options.timeout * 1000);
                window[cbName] = function (result) {
                    console.log('result from native:', JSON.stringify(result));
                    if (result) {
                        var code = result.code;
                        var msg = result.msg;
                        var errCode = result.eCode;
                        var data = result.data;
                        if (code == 0) {
                            resolve(data);
                        }
                        else {
                            reject({ code: errCode, msg: msg });
                        }
                    }
                    else {
                        reject({ code: ERROR_CODE_UNKNOW, msg: 'result is null' });
                    }
                    _this.clearCallback(cbName, timeoutId, cbProgressName);
                };
                window[cbProgressName] = function (progressData) {
                    cc.log('invoke data', JSON.stringify(progressData));
                    if (_this._options.onProgress && progressData) {
                        var code = progressData.code;
                        var msg = progressData.msg;
                        var errCode = progressData.eCode;
                        var data = progressData.data;
                        if (code == 0) {
                            _this._options.onProgress(data);
                        }
                        else {
                            cc.log("progress error: " + code + ", " + errCode + "," + msg);
                        }
                    }
                };
            }
            if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
                var resultCode = jsb.reflection.callStaticMethod('com/tencent/cocomat/binding/CCMBinding', 'execute', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I', methodName, typeof args === 'object' ? JSON.stringify(args) : '', cbName);
                if (resultCode !== 0) {
                    switch (resultCode) {
                        case -1:
                            reject({
                                code: ERROR_CODE_METHOD_NOT_DEFINED,
                                msg: methodName + " not found on Android platform"
                            });
                            break;
                        case -2:
                            reject({ code: ERROR_CODE_PARAMS_ERROR, msg: "error! invalid parameters" });
                            break;
                        default:
                            reject({ code: resultCode, msg: "error! result code=" + resultCode });
                            break;
                    }
                    if (hasCallback) {
                        _this.clearCallback(cbName, timeoutId, cbProgressName);
                    }
                }
            }
            else if (cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS) {
                var retId = jsb.reflection.callStaticMethod('CCMBinding', 'executeWithMethodName:args:callback:', methodName, typeof args === 'object' ? JSON.stringify(args) : '', cbName);
            }
            else {
                var msg = 'no implemented on this platform';
                reject({ code: ERROR_CODE_METHOD_NOT_DEFINED, msg: msg });
                _this.clearCallback(cbName, timeoutId, cbProgressName);
            }
        });
    };
    CCMBinding.prototype.clearCallback = function (cbName, timeoutId, cbProgressName) {
        if (timeoutId === void 0) { timeoutId = -1; }
        if (cbProgressName === void 0) { cbProgressName = ''; }
        if (cbProgressName && cbProgressName != '') {
            console.log("delete cbProgressName" + cbName);
            delete window[cbProgressName];
        }
        if (cbName && cbName != '') {
            console.log("delete cbName" + cbName);
            delete window[cbName];
        }
        if (timeoutId >= 0) {
            console.log("clearTimeout" + cbName);
            clearTimeout(timeoutId);
        }
    };
    return CCMBinding;
}());
exports.default = CCMBinding;

cc._RF.pop();