// 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 { createParticipantModifier } from '../utils';
/**
 * @private
 */
export const createProfileStateModifier = (onFetchProfile, notifyUpdate) => {
    const cachedDisplayName = {};
    return (state) => {
        var _a;
        const originalParticipants = (_a = state.call) === null || _a === void 0 ? void 0 : _a.remoteParticipants;
        (() => __awaiter(void 0, void 0, void 0, function* () {
            let shouldNotifyUpdates = false;
            if (!originalParticipants) {
                return;
            }
            for (const [key, participant] of Object.entries(originalParticipants)) {
                if (cachedDisplayName[key]) {
                    continue;
                }
                const profile = yield onFetchProfile(key, {
                    displayName: participant.displayName
                });
                if ((profile === null || profile === void 0 ? void 0 : profile.displayName) && participant.displayName !== (profile === null || profile === void 0 ? void 0 : profile.displayName)) {
                    cachedDisplayName[key] = profile === null || profile === void 0 ? void 0 : profile.displayName;
                    shouldNotifyUpdates = true;
                }
            }
            // notify update only when there is a change, which most likely will trigger modifier and setState again
            if (shouldNotifyUpdates) {
                notifyUpdate();
            }
        }))();
        const participantsModifier = createParticipantModifier((id, participant) => {
            if (cachedDisplayName[id]) {
                return Object.assign(Object.assign({}, participant), { displayName: cachedDisplayName[id] });
            }
            return undefined;
        });
        return participantsModifier(state);
    };
};
//# sourceMappingURL=OnFetchProfileCallback.js.map