"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const StringUtils_1 = require("./util/StringUtils");
function _isReactNativeGlobal(globalScope) {
    return globalScope.ErrorUtils !== undefined;
}
exports.ErrorHandler = (Cloudwise, Logger) => {
    return {
        registerErrorHandler() {
            if (global !== undefined && _isReactNativeGlobal(global)) {
                const oldHandler = global.ErrorUtils.getGlobalHandler();
                global.ErrorUtils.setGlobalHandler((error, isFatal) => {
                    this._reportErrorToCloudwise(error, isFatal, oldHandler);
                });
                const setter = global.ErrorUtils.setGlobalHandler;
                global.ErrorUtils.setGlobalHandler = (errorHandler) => {
                    setter((error, isFatal) => {
                        this._reportErrorToCloudwise(error, isFatal, errorHandler);
                    });
                };
            }
        },
        _reportErrorToCloudwise(exception, isFatal, oldHandler) {
            if (exception && isExceptionAnError(exception)) {
                if (!StringUtils_1.StringUtils.isStringNullEmptyOrWhitespace(exception.name)) {
                    if (isFatal === undefined) {
                        isFatal = false;
                    }
                    if (exception.stack) {
                        Cloudwise.reportErrorWithStacktrace(isFatal, String(exception.name), String(exception.message), exception.stack);
                        Logger.log("Report Error with stacktrace: " + exception.message);
                    }
                    else {
                        Cloudwise.reportError(String(exception.name) + ": " + String(exception.message), -1);
                        Logger.log("Report Error: " + exception);
                    }
                }
            }
            else {
                Cloudwise.reportError(String(exception), -1);
                Logger.log("Report Error: " + exception);
            }
            if (oldHandler !== undefined) {
                oldHandler(exception, isFatal);
            }
        }
    };
};
function isExceptionAnError(exception) {
    return exception.message != undefined;
}
