// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { getTypingIndicators, getParticipants, getUserId } from './baseSelectors';
import { createSelector } from 'reselect';
import { toFlatCommunicationIdentifier } from "../../acs-ui-common/src";
import { MINIMUM_TYPING_INTERVAL_IN_MILLISECONDS, PARTICIPANTS_THRESHOLD } from './utils/constants';
const filterTypingIndicators = (typingIndicators, userId) => {
    const filteredTypingIndicators = [];
    const seen = new Set();
    const date8SecondsAgo = new Date(Date.now() - MINIMUM_TYPING_INTERVAL_IN_MILLISECONDS);
    const reversedTypingIndicators = typingIndicators.toReversed();
    for (const typingIndicator of reversedTypingIndicators) {
        if (toFlatCommunicationIdentifier(typingIndicator.sender) === userId) {
            continue;
        }
        if (typingIndicator.receivedOn < date8SecondsAgo) {
            continue;
        }
        if (seen.has(toFlatCommunicationIdentifier(typingIndicator.sender))) {
            continue;
        }
        seen.add(toFlatCommunicationIdentifier(typingIndicator.sender));
        filteredTypingIndicators.push(typingIndicator);
    }
    return filteredTypingIndicators;
};
const convertSdkTypingIndicatorsToCommunicationParticipants = (typingIndicators, participants) => {
    return typingIndicators.map(typingIndicator => {
        var _a;
        return ({
            userId: toFlatCommunicationIdentifier(typingIndicator.sender),
            displayName: (_a = participants[toFlatCommunicationIdentifier(typingIndicator.sender)]) === null || _a === void 0 ? void 0 : _a.displayName
        });
    });
};
/**
 * Selector for {@link TypingIndicator} component.
 *
 * @public
 */
export const typingIndicatorSelector = createSelector([getTypingIndicators, getParticipants, getUserId], (typingIndicators, participants, userId) => {
    // if the participant size reaches the threshold then return no typing users
    if (Object.values(participants).length >= PARTICIPANTS_THRESHOLD) {
        return {
            typingUsers: []
        };
    }
    // filter typing indicators to remove those that are from the duplicate users or current user as well as those older than a threshold
    const filteredTypingIndicators = filterTypingIndicators(typingIndicators, userId);
    const typingUsers = convertSdkTypingIndicatorsToCommunicationParticipants(filteredTypingIndicators, participants);
    return {
        typingUsers
    };
});
//# sourceMappingURL=typingIndicatorSelector.js.map