// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
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 { Features, LocalVideoStream } from '@azure/communication-calling';
import { isCommunicationUserIdentifier, isMicrosoftTeamsUserIdentifier, isPhoneNumberIdentifier } from '@azure/communication-common';
import { memoizeFnAll, toFlatCommunicationIdentifier } from "../../../acs-ui-common/src";
/**
 * Check if the call state represents being in the call
 *
 * @internal
 */
export const _isInCall = (callStatus) => !!callStatus && !['None', 'Disconnected', 'Connecting', 'Ringing', 'EarlyMedia', 'Disconnecting'].includes(callStatus);
/**
 * Check if the call state represents being in the lobby or waiting to be admitted.
 *
 * @internal
 */
export const _isInLobbyOrConnecting = (callStatus) => !!callStatus && ['Connecting', 'Ringing', 'InLobby', 'EarlyMedia'].includes(callStatus);
/**
 * Check if the device manager local video is on when not part of a call
 * i.e. do unparented views exist.
 *
 * @internal
 */
export const _isPreviewOn = (deviceManager) => {
    var _a;
    // TODO: we should take in a LocalVideoStream that developer wants to use as their 'Preview' view. We should also
    // handle cases where 'Preview' view is in progress and not necessary completed.
    return ((_a = deviceManager.unparentedViews[0]) === null || _a === void 0 ? void 0 : _a.view) !== undefined;
};
/**
 * Dispose of all preview views
 * We assume all unparented views are local preview views.
 *
 * @private
 */
export const disposeAllLocalPreviewViews = (callClient) => __awaiter(void 0, void 0, void 0, function* () {
    const unparentedViews = callClient.getState().deviceManager.unparentedViews;
    for (const view of unparentedViews) {
        yield callClient.disposeView(undefined, undefined, view);
    }
});
/**
 * Update the users displayNames based on the type of user they are
 *
 * @internal
 */
export const _updateUserDisplayNames = (participants) => {
    if (participants) {
        return memoizedUpdateDisplayName(memoizedFn => {
            return Object.values(participants).map(p => {
                const pid = toFlatCommunicationIdentifier(p.identifier);
                return memoizedFn(pid, p);
            });
        });
    }
    else {
        return [];
    }
};
/**
 * Get the display name of a participant for given userId
 *
 * @internal
 *
 */
export const getRemoteParticipantDisplayName = (participantUserId, remoteParticipants) => {
    let displayName;
    if (remoteParticipants) {
        const participant = remoteParticipants[participantUserId];
        if (participant) {
            displayName = participant.displayName;
        }
    }
    return displayName;
};
const memoizedUpdateDisplayName = memoizeFnAll((participantId, participant) => {
    if (isPhoneNumberIdentifier(participant.identifier)) {
        return Object.assign(Object.assign({}, participant), { displayName: participant.identifier.phoneNumber });
    }
    else {
        return participant;
    }
});
/**
 * Check whether the call is in a supported browser
 *
 * @internal
 */
export const _getEnvironmentInfo = (callClient) => __awaiter(void 0, void 0, void 0, function* () {
    const environmentInfo = yield callClient.feature(Features.DebugInfo).getEnvironmentInfo();
    return environmentInfo;
});
/**
 * @private
 * A type guard to ensure all participants are acceptable type for Teams call
 */
export const isTeamsCallParticipants = (participants) => {
    return participants.every(p => !isCommunicationUserIdentifier(p));
};
/**
 * @private
 * A type guard to ensure all participants are acceptable type for ACS call
 */
export const isACSCallParticipants = (participants) => {
    return participants.every(p => !isMicrosoftTeamsUserIdentifier(p));
};
/**
 * @private
 * Checks whether the user is a 'Ringing' PSTN user or in a 'Connecting' state.
 */
export const _convertParticipantState = (participant) => {
    return isPhoneNumberIdentifier(participant.identifier) && participant.state === 'Connecting' ? 'Ringing' : participant.state;
};
/**
 * @private
 * Changes the display name of the participant based on the local and remote user's role.
 */
export const maskDisplayNameWithRole = (displayName, localUserRole, participantRole, isHideAttendeeNamesEnabled) => {
    let maskedDisplayName = displayName;
    if (isHideAttendeeNamesEnabled && participantRole && participantRole === 'Attendee') {
        if (localUserRole && localUserRole === 'Attendee') {
            maskedDisplayName = '{AttendeeRole}';
        }
        if (localUserRole && (localUserRole === 'Presenter' || localUserRole === 'Co-organizer' || localUserRole === 'Organizer')) {
            maskedDisplayName = `{AttendeeRole}(${displayName})`;
        }
    }
    return maskedDisplayName;
};
/**
 * Helper to create a local video stream from the selected camera.
 * @private
 */
export const createLocalVideoStream = (callClient) => __awaiter(void 0, void 0, void 0, function* () {
    const camera = yield (callClient === null || callClient === void 0 ? void 0 : callClient.getState().deviceManager.selectedCamera);
    if (camera) {
        return new LocalVideoStream(camera);
    }
    return undefined;
});
/**
 * Get call state if existing, if not and the call not exists in ended record return undefined, if it never exists, throw an error.
 * @private
 */
export const getCallStateIfExist = (state, callId) => {
    if (!state.calls[callId]) {
        // If call has ended, we don't need to throw an error.
        if (state.callsEnded[callId]) {
            return undefined;
        }
        throw new Error(`Call Not Found: ${callId}`);
    }
    return state.calls[callId];
};
//# sourceMappingURL=callUtils.js.map