import logger from './logger';
import { STORAGE_PREFIX } from './constants';
export const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));
export const objEmpty = (obj) => Object.keys(obj).length === 0;
export const mutateStorageKey = (key) => `${STORAGE_PREFIX}${key}`;
export const mutateLiveArrayData = (data) => {
    const [participantId, participantNumber, participantName, codec, mediaJson, participantData] = data;
    let media = {};
    try {
        media = JSON.parse(mediaJson.replace(/ID"/g, 'Id"'));
    }
    catch (error) {
        logger.warn('Verto LA invalid media JSON string:', mediaJson);
    }
    return { participantId: Number(participantId), participantNumber, participantName, codec, media, participantData };
};
export const safeParseJson = (value) => {
    if (typeof value !== 'string') {
        return value;
    }
    try {
        return JSON.parse(value);
    }
    catch (error) {
        return value;
    }
};
export const isDefined = (variable) => typeof variable !== 'undefined';
export const isFunction = (variable) => variable instanceof Function || typeof variable === 'function';
export const findElementByType = (tag) => {
    if (typeof document !== 'object' || !('getElementById' in document)) {
        return null;
    }
    if (typeof tag === 'string') {
        return document.getElementById(tag) || null;
    }
    else if (typeof tag === 'function') {
        return tag();
    }
    else if (tag instanceof HTMLMediaElement) {
        return tag;
    }
    return null;
};
const PROTOCOL_PATTERN = /^(ws|wss):\/\//;
export const checkWebSocketHost = (host, security) => {
    let protocol = security ? `wss://` : `ws://`;
    protocol = PROTOCOL_PATTERN.test(host) ? '' : protocol;
    return `${protocol}${host}/stream`;
};
export const destructResponse = (response, nodeId = null) => {
    const { result = {}, error } = response;
    if (error) {
        return { error };
    }
    const { result: nestedResult = null } = result;
    if (nestedResult === null) {
        if (nodeId !== null) {
            result.node_id = nodeId;
        }
        return { result };
    }
    const { code = null, node_id = null, result: vertoResult = null } = nestedResult;
    if (code && code !== '200') {
        return { error: nestedResult };
    }
    if (vertoResult) {
        return destructResponse(vertoResult, node_id);
    }
    return { result: nestedResult };
};
export const randomInt = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min);
};
