"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.logPendingSession = exports.isPeerConnectionDisconnected = exports.isVideoJid = exports.isLiveScreenMonitorJid = exports.isAgentVideoJid = exports.isPeerVideoJid = exports.isSoftphoneJid = exports.isScreenRecordingJid = exports.isAcdJid = exports.requestApi = exports.requestApiWithRetry = exports.defaultConfigOption = exports.createAndEmitSdkError = exports.SdkError = void 0;
exports.buildRequestApiOptions = buildRequestApiOptions;
exports.getBareJid = getBareJid;
exports.delay = delay;
exports.removeAddressFieldFromConversationUpdate = removeAddressFieldFromConversationUpdate;
const enums_1 = require("./types/enums");
class SdkError extends Error {
    // ignoring this due to a coverage issue relating to babel. https://github.com/Microsoft/TypeScript/issues/13029
    /* istanbul ignore next */
    constructor(errorType, messageOrError, details) {
        /* if a Error is passed in, use its message and name properties */
        const isError = messageOrError && messageOrError instanceof Error;
        super(isError ? messageOrError.message : messageOrError);
        if (isError) {
            this.name = messageOrError.name;
        }
        this.type = errorType || enums_1.SdkErrorTypes.generic;
        this.details = details;
    }
}
exports.SdkError = SdkError;
/**
 * This will create an `SdkError`, emit the error on `sdk.on('sdkError', error)`,
 *  and return the error. It will not `throw` the error. It is up to the caller
 *  on what to do with it.
 * @param this sdk instance
 * @param errorType SdkError type
 * @param message message as string or Error instance
 * @param details any additional details to log with the error
 */
const createAndEmitSdkError = function (errorType, messageOrError, details) {
    const error = new SdkError(errorType, messageOrError, details);
    // Isolate us from any downstream throws
    setTimeout(() => {
        this.emit('sdkError', error);
    }, 0);
    return error;
};
exports.createAndEmitSdkError = createAndEmitSdkError;
const defaultConfigOption = function (providedOption, defaultValue, defaultConditions = { undefined: true, null: true, falsy: false }) {
    const undefCondition = typeof providedOption === 'undefined' && defaultConditions.undefined;
    const nullCondition = providedOption === null && defaultConditions.null;
    const falsyCondition = !providedOption && defaultConditions.falsy;
    if (undefCondition || nullCondition || falsyCondition) {
        return defaultValue;
    }
    return providedOption;
};
exports.defaultConfigOption = defaultConfigOption;
const requestApiWithRetry = function (path, opts = {}) {
    opts = buildRequestApiOptions(this, opts);
    const request = this._http.requestApiWithRetry(path, opts);
    request.promise.catch(e => exports.createAndEmitSdkError.call(this, enums_1.SdkErrorTypes.http, e.message, e));
    return request;
};
exports.requestApiWithRetry = requestApiWithRetry;
const requestApi = function (path, opts = {}) {
    opts = buildRequestApiOptions(this, opts);
    return this._http.requestApi(path, opts)
        .catch(e => { exports.createAndEmitSdkError.call(this, enums_1.SdkErrorTypes.http, e.message, e); throw e; });
};
exports.requestApi = requestApi;
function buildRequestApiOptions(sdk, opts = {}) {
    if (!opts.noAuthHeader) {
        opts.authToken = opts.authToken || sdk._config.accessToken;
    }
    if (!opts.host) {
        opts.host = sdk._config.environment;
    }
    if (!opts.method) {
        opts.method = 'get';
    }
    if (!opts.customHeaders && sdk._config.customHeaders) {
        opts.customHeaders = sdk._config.customHeaders;
    }
    opts.customHeaders = {
        ...(sdk._config.customHeaders || {}),
        ...(opts.customHeaders || {})
    };
    return opts;
}
const isAcdJid = function (jid) {
    return jid.startsWith('acd-');
};
exports.isAcdJid = isAcdJid;
const isScreenRecordingJid = function (jid) {
    return jid.startsWith('screenrecording-');
};
exports.isScreenRecordingJid = isScreenRecordingJid;
const isSoftphoneJid = function (jid) {
    if (!jid) {
        return false;
    }
    return !!jid.match(/.*@.*gjoll.*/i);
};
exports.isSoftphoneJid = isSoftphoneJid;
const isPeerVideoJid = function (jid) {
    return (0, exports.isVideoJid)(jid) && jid.startsWith('peer-');
};
exports.isPeerVideoJid = isPeerVideoJid;
const isAgentVideoJid = function (jid) {
    return (0, exports.isVideoJid)(jid) && jid.startsWith('agent-');
};
exports.isAgentVideoJid = isAgentVideoJid;
const isLiveScreenMonitorJid = function (jid) {
    return jid.startsWith('livemonitor-');
};
exports.isLiveScreenMonitorJid = isLiveScreenMonitorJid;
const isVideoJid = function (jid) {
    return jid && !!jid.match(/@conference/) && !(0, exports.isAcdJid)(jid) && !(0, exports.isScreenRecordingJid)(jid) && !(0, exports.isLiveScreenMonitorJid)(jid);
};
exports.isVideoJid = isVideoJid;
const isPeerConnectionDisconnected = function (state) {
    const disconnectedStates = ['interrupted', 'disconnected', 'failed', 'closed'];
    return disconnectedStates.includes(state);
};
exports.isPeerConnectionDisconnected = isPeerConnectionDisconnected;
const logPendingSession = function (logger, message, pendingSession, level = 'info') {
    const data = {
        sessionId: pendingSession.id || pendingSession.sessionId,
        autoAnswer: pendingSession.autoAnswer,
        conversationId: pendingSession.conversationId,
        fromUserId: pendingSession.fromUserId,
        meetingId: pendingSession.meetingId
    };
    /* for pending sessions */
    if (pendingSession.sessionType) {
        data.sessionType = pendingSession.sessionType;
    }
    logger[level](message, data);
};
exports.logPendingSession = logPendingSession;
function getBareJid(sdk) {
    return sdk._streamingConnection.config.jid;
}
async function delay(timeMs) {
    await new Promise((resolve) => {
        setTimeout(resolve, timeMs);
    });
}
function removeAddressFieldFromConversationUpdate(update) {
    if (Array.isArray(update)) {
        return update.map(removeAddressFieldFromConversationUpdate);
    }
    else if (update && typeof update === 'object') {
        const clone = {};
        for (const [key, value] of Object.entries(update)) {
            if (key !== 'address') {
                clone[key] = removeAddressFieldFromConversationUpdate(value);
            }
        }
        return clone;
    }
    return update;
}
//# sourceMappingURL=utils.js.map