var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { SdkErrorTypes } from './types/enums';
export 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 || SdkErrorTypes.generic;
        this.details = details;
    }
}
/**
 * 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
 */
export 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;
};
export 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;
};
export const requestApiWithRetry = function (path, opts = {}) {
    opts = buildRequestApiOptions(this, opts);
    const request = this._http.requestApiWithRetry(path, opts);
    request.promise.catch(e => createAndEmitSdkError.call(this, SdkErrorTypes.http, e.message, e));
    return request;
};
export const requestApi = function (path, opts = {}) {
    opts = buildRequestApiOptions(this, opts);
    return this._http.requestApi(path, opts)
        .catch(e => { createAndEmitSdkError.call(this, SdkErrorTypes.http, e.message, e); throw e; });
};
export 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 = Object.assign(Object.assign({}, (sdk._config.customHeaders || {})), (opts.customHeaders || {}));
    return opts;
}
export const isAcdJid = function (jid) {
    return jid.startsWith('acd-');
};
export const isScreenRecordingJid = function (jid) {
    return jid.startsWith('screenrecording-');
};
export const isSoftphoneJid = function (jid) {
    if (!jid) {
        return false;
    }
    return !!jid.match(/.*@.*gjoll.*/i);
};
export const isPeerVideoJid = function (jid) {
    return isVideoJid(jid) && jid.startsWith('peer-');
};
export const isAgentVideoJid = function (jid) {
    return isVideoJid(jid) && jid.startsWith('agent-');
};
export const isLiveScreenMonitorJid = function (jid) {
    return jid.startsWith('livemonitor-');
};
export const isVideoJid = function (jid) {
    return jid && !!jid.match(/@conference/) && !isAcdJid(jid) && !isScreenRecordingJid(jid) && !isLiveScreenMonitorJid(jid);
};
export const isPeerConnectionDisconnected = function (state) {
    const disconnectedStates = ['interrupted', 'disconnected', 'failed', 'closed'];
    return disconnectedStates.includes(state);
};
export 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);
};
export function getBareJid(sdk) {
    return sdk._streamingConnection.config.jid;
}
export function delay(timeMs) {
    return __awaiter(this, void 0, void 0, function* () {
        yield new Promise((resolve) => {
            setTimeout(resolve, timeMs);
        });
    });
}
export 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