'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index$1 = require('./index-2e5758b6.js');
const notification = require('./notification-8f4db150.js');
const string = require('./string-9bce3253.js');
const uiStore = require('./ui-store-583d205a.js');
const chat = require('./chat-a1c8f378.js');
const index = require('./index-3f8e5441.js');
require('./browser-5538db4d.js');

const DEFAULT_NOTIFICATION_DURATION = 2000;
const DEFAULT_NOTIFICATION_CONFIG = Object.freeze({
    notifications: {
        participant_joined: true,
        participant_left: true,
        participant_joined_waitlist: true,
        chat: true,
        polls: true,
        webinar: true,
        tab_sync: true,
        recording_started: true,
        recording_stopped: true,
    },
    notification_sounds: {
        participant_joined: true,
        participant_left: true,
        chat: true,
        polls: true,
        webinar: true,
        participant_joined_waitlist: true,
    },
    notification_duration: {
        participant_joined: 2100,
        participant_left: 2100,
        participant_joined_waitlist: 4000,
        chat: DEFAULT_NOTIFICATION_DURATION,
        polls: DEFAULT_NOTIFICATION_DURATION,
        webinar: DEFAULT_NOTIFICATION_DURATION,
        tab_sync: DEFAULT_NOTIFICATION_DURATION,
        recording_started: DEFAULT_NOTIFICATION_DURATION,
        recording_stopped: DEFAULT_NOTIFICATION_DURATION,
    },
    participant_joined_sound_notification_limit: 10,
    participant_chat_message_sound_notification_limit: 10,
});

const rtkNotificationsCss = ":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}:host{position:absolute;top:var(--rtk-space-4, 16px);right:var(--rtk-space-4, 16px);bottom:var(--rtk-space-4, 16px);left:var(--rtk-space-4, 16px);top:auto;display:flex;flex-direction:column;pointer-events:none;z-index:100}rtk-notification{margin-top:var(--rtk-space-2, 8px)}";
const RtkNotificationsStyle0 = rtkNotificationsCss;

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
        r = Reflect.decorate(decorators, target, key, desc);
    else
        for (var i = decorators.length - 1; i >= 0; i--)
            if (d = decorators[i])
                r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
function parseConfig(config) {
    const permissions = Object.assign({}, DEFAULT_NOTIFICATION_CONFIG);
    if (config == null)
        return permissions;
    Object.assign(permissions.notification_sounds, config.notification_sounds);
    Object.assign(permissions.notifications, config.notifications);
    Object.assign(permissions.notification_duration, config.notification_duration);
    permissions.participant_chat_message_sound_notification_limit =
        config.participant_chat_message_sound_notification_limit;
    permissions.participant_joined_sound_notification_limit =
        config.participant_joined_sound_notification_limit;
    return permissions;
}
function getEnabledSounds(sounds) {
    return Object.keys(sounds).filter((key) => sounds[key]);
}
const RtkNotifications = class {
    constructor(hostRef) {
        index$1.registerInstance(this, hostRef);
        this.permissions = DEFAULT_NOTIFICATION_CONFIG;
        this.enabledSounds = getEnabledSounds(DEFAULT_NOTIFICATION_CONFIG.notification_sounds);
        /** Config object */
        this.config = uiStore.createDefaultConfig();
        /** Language */
        this.t = uiStore.useLanguage();
        /** Icon pack */
        this.iconPack = uiStore.defaultIconPack;
        this.notifications = [];
        this.addStagePeersListeners = (meeting) => {
            meeting.participants.joined.addListener('participantJoined', this.participantJoinedListener);
            meeting.participants.joined.addListener('participantLeft', this.participantLeftListener);
        };
        this.removeStagePeersListeners = (meeting) => {
            meeting.participants.joined.removeListener('participantJoined', this.participantJoinedListener);
            meeting.participants.joined.removeListener('participantLeft', this.participantLeftListener);
        };
        this.onNotification = (e) => {
            this.add(e.detail);
            const playSound = e.detail.playSound;
            if (playSound != undefined)
                this.audio.play(playSound);
        };
        this.onRecordingUpdate = (recordingState) => {
            var _a, _b;
            if (recordingState === 'RECORDING' &&
                this.permissions.notifications.recording_started !== false) {
                this.add({
                    id: 'recording-started',
                    icon: this.iconPack.recording,
                    message: this.t('recording.started'),
                    duration: (_a = this.permissions.notification_duration.recording_started) !== null && _a !== void 0 ? _a : DEFAULT_NOTIFICATION_DURATION,
                });
            }
            else if (recordingState === 'STOPPING' &&
                this.permissions.notifications.recording_stopped !== false) {
                this.add({
                    id: 'recording-stopped',
                    icon: this.iconPack.stop_recording,
                    message: this.t('recording.stopped'),
                    duration: (_b = this.permissions.notification_duration.recording_stopped) !== null && _b !== void 0 ? _b : DEFAULT_NOTIFICATION_DURATION,
                });
            }
        };
        this.paused = false;
    }
    connectedCallback() {
        if (typeof document !== 'undefined') {
            document === null || document === void 0 ? void 0 : document.addEventListener('rtkNotification', this.onNotification);
        }
        this.meetingChanged(this.meeting);
        this.configChanged(this.config);
        this.statesChanged(this.states);
    }
    clearListeners(meeting) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const isLivestream = meeting.meta.viewType === 'LIVESTREAM';
        if ((isLivestream && ((_a = meeting.stage) === null || _a === void 0 ? void 0 : _a.status) === 'ON_STAGE') || !isLivestream) {
            this.removeStagePeersListeners(meeting);
        }
        this.chatUpdateListener && ((_b = meeting.chat) === null || _b === void 0 ? void 0 : _b.removeListener('chatUpdate', this.chatUpdateListener));
        this.pollUpdateListener &&
            ((_c = meeting.polls) === null || _c === void 0 ? void 0 : _c.removeListener('pollsUpdate', this.pollUpdateListener));
        meeting.meta.removeListener('socketConnectionUpdate', this.socketConnectionUpdateListener);
        this.stageRequestAccepted &&
            ((_d = meeting.stage) === null || _d === void 0 ? void 0 : _d.removeListener('stageRequestApproved', this.stageRequestAccepted));
        this.stageRequestRejected &&
            ((_e = meeting.stage) === null || _e === void 0 ? void 0 : _e.removeListener('stageRequestRejected', this.stageRequestRejected));
        this.newStageRequests &&
            ((_f = meeting.stage) === null || _f === void 0 ? void 0 : _f.removeListener('newStageRequest', this.newStageRequests));
        this.stageStatusUpdateListener &&
            ((_g = meeting.stage) === null || _g === void 0 ? void 0 : _g.removeListener('stageStatusUpdate', this.stageStatusUpdateListener));
        (_h = meeting.recording) === null || _h === void 0 ? void 0 : _h.removeListener('recordingUpdate', this.onRecordingUpdate);
        clearTimeout(this.disconnectTimeout);
        meeting.self.removeListener('deviceUpdate', this.deviceUpdateListener);
    }
    disconnectedCallback() {
        var _a;
        if (typeof document !== 'undefined') {
            document === null || document === void 0 ? void 0 : document.removeEventListener('rtkNotification', this.onNotification);
        }
        if (!this.meeting)
            return;
        this.clearListeners(this.meeting);
        this.waitlistedParticipantJoinedListener &&
            this.meeting.participants.waitlisted.removeListener('participantJoined', this.waitlistedParticipantJoinedListener);
        this.waitlistedParticipantLeftListener &&
            this.meeting.participants.waitlisted.removeListener('participantLeft', this.waitlistedParticipantLeftListener);
        this.activeTabUpdateListener &&
            ((_a = this.meeting.meta) === null || _a === void 0 ? void 0 : _a.removeListener('activeTabUpdate', this.activeTabUpdateListener));
        this.peerStageStatusListener &&
            this.meeting.participants.joined.removeListener('stageStatusUpdate', this.peerStageStatusListener);
    }
    meetingChanged(meeting, oldMeeting) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        clearTimeout(this.disconnectTimeout);
        if (oldMeeting)
            this.clearListeners(oldMeeting);
        if (!meeting)
            return;
        const isLivestream = meeting.meta.viewType === 'LIVESTREAM';
        this.audio = new notification.RTKNotificationsAudio(meeting);
        const { notifications, notification_duration, notification_sounds } = this.permissions;
        this.participantJoinedListener = (participant) => {
            if (notifications.participant_joined) {
                this.add({
                    id: `${participant.id}-joined`,
                    message: `${string.formatName(participant.name)} ${this.t('notifications.joined')}`,
                    image: participant.picture,
                    duration: notification_duration.participant_joined,
                });
            }
            if (notification_sounds.participant_joined && this.canPlayParticipantJoinedSound()) {
                this.audio.play('joined');
            }
        };
        this.participantLeftListener = (participant) => {
            const { socketState: { state }, } = this.meeting.meta;
            if (notifications.participant_left && state !== 'connected') {
                this.add({
                    id: `${participant.id}-left`,
                    message: `${string.formatName(participant.name)} ${this.t('notifications.left')}`,
                    image: participant.picture,
                    duration: notification_duration.participant_left,
                });
            }
            if (notification_sounds.participant_left && this.canPlayParticipantJoinedSound()) {
                this.audio.play('left');
            }
        };
        this.waitlistedParticipantJoinedListener = (participant) => {
            if (!this.canAcceptWaitingRequests())
                return;
            const id = `${participant.id}-joined-waitlist`;
            this.add({
                id,
                message: `${string.formatName(participant.name)} ${this.t('notifications.requesting_to_join_meeting')}`,
                image: participant.picture,
                duration: notification_duration.participant_joined_waitlist,
                button: {
                    text: this.t('notifications.accept'),
                    variant: 'primary',
                    onClick: async () => {
                        await this.meeting.participants.acceptWaitingRoomRequest(participant.id);
                        this.remove(id);
                    },
                },
            });
            if (notification_sounds.participant_joined_waitlist && this.canPlayParticipantJoinedSound()) {
                this.audio.play('message');
            }
        };
        this.waitlistedParticipantLeftListener = (participant) => {
            this.remove(`${participant.id}-joined-waitlist`);
        };
        this.chatUpdateListener = ({ message, action }) => {
            // NOTE(ikabra): we only want notifications for new messages
            if (action !== 'add')
                return;
            const parsedMessage = chat.parseMessageForTarget(message);
            if (parsedMessage != null) {
                if (parsedMessage.userId === meeting.self.userId) {
                    return;
                }
                if (parsedMessage.type === 'text') {
                    if (notifications.chat) {
                        this.add({
                            id: `message-${Math.random().toString(36)}`,
                            icon: this.iconPack.chat,
                            message: `${parsedMessage.displayName}: ${parsedMessage.message}`,
                            duration: notification_duration.chat,
                        });
                    }
                    if (notification_sounds.chat && this.canPlayChatSound()) {
                        this.audio.play('message');
                    }
                }
            }
        };
        this.pollUpdateListener = ({ polls, newPoll }) => {
            if (newPoll === false)
                return;
            if (notifications.polls &&
                this.meeting.self.userId !== polls[polls.length - 1].createdByUserId) {
                this.add({
                    id: `poll-${Math.random().toString(36)}`,
                    icon: this.iconPack.poll,
                    message: `${this.t('notifications.new_poll_created_by')} ${polls[polls.length - 1].createdBy}`,
                    duration: notification_duration.polls,
                });
            }
            if (notification_sounds.polls &&
                this.meeting.self.userId !== polls[polls.length - 1].createdByUserId &&
                this.canPlayChatSound()) {
                this.audio.play('message');
            }
        };
        this.deviceUpdateListener = ({ device, preview }) => {
            if (preview)
                return;
            if (device.kind === 'audiooutput') {
                this.audio.setDevice(device.deviceId);
                this.remove(`speaker-switched`);
                this.add({
                    id: `speaker-switched`,
                    message: `${this.t('notifications.connected_to')} ${device.label}`,
                    icon: this.iconPack.speaker,
                    duration: 5000,
                });
            }
            if (device.kind === 'videoinput') {
                this.remove(`camera-switched`);
                this.add({
                    id: `camera-switched`,
                    message: `${this.t('notifications.connected_to')} ${device.label}`,
                    icon: this.meeting.self.videoEnabled ? this.iconPack.video_on : this.iconPack.video_off,
                    iconVariant: this.meeting.self.videoEnabled ? 'primary' : 'danger',
                    duration: 5000,
                });
            }
            if (device.kind === 'audioinput') {
                this.remove(`mic-switched`);
                this.add({
                    id: `mic-switched`,
                    message: `${this.t('notifications.connected_to')} ${device.label}`,
                    icon: this.meeting.self.audioEnabled ? this.iconPack.mic_on : this.iconPack.mic_off,
                    iconVariant: this.meeting.self.audioEnabled ? 'primary' : 'danger',
                    duration: 5000,
                });
            }
        };
        this.socketConnectionUpdateListener = ({ state, reconnectionAttempt, reconnected }) => {
            switch (state) {
                case 'connected':
                    this.remove('socket');
                    if (reconnected)
                        this.add({
                            id: `socket`,
                            icon: this.iconPack.wifi,
                            message: this.t('network.restored'),
                            duration: 3000,
                        });
                    break;
                case 'disconnected':
                    this.remove('socket');
                    this.add({
                        id: 'socket',
                        icon: this.iconPack.disconnected,
                        message: this.t('network.reconnecting'),
                    });
                    break;
                case 'reconnecting':
                    if (reconnectionAttempt >= 6) {
                        this.remove('socket');
                        this.add({
                            id: 'socket',
                            icon: this.iconPack.disconnected,
                            message: this.t('network.disconnected'),
                            button: {
                                text: this.t('end'),
                                variant: 'danger',
                                onClick: () => { var _a; return (_a = this.meeting) === null || _a === void 0 ? void 0 : _a.leave(); },
                            },
                        });
                    }
                    else if (reconnectionAttempt >= 4) {
                        this.remove('socket');
                        this.add({
                            id: 'socket',
                            icon: this.iconPack.disconnected,
                            message: this.t('network.delay_extended'),
                        });
                    }
                    break;
                case 'failed':
                    this.remove('socket');
                    this.add({
                        id: 'socket',
                        icon: this.iconPack.disconnected,
                        message: this.t('network.leaving'),
                        button: {
                            text: this.t('end'),
                            variant: 'danger',
                            onClick: () => { var _a; return (_a = this.meeting) === null || _a === void 0 ? void 0 : _a.leave(); },
                        },
                    });
                    break;
            }
        };
        this.activeTabUpdateListener = (activeTab) => {
            if (!notifications.tab_sync)
                return;
            switch (activeTab.type) {
                case 'plugin':
                    const activePlugin = meeting.plugins.active
                        .toArray()
                        .find((plugin) => plugin.id == activeTab.id);
                    if (activePlugin != undefined) {
                        this.add({
                            id: 'activeTab',
                            message: `${this.t('notifications.plugin_switched_to')} ${activePlugin.name}`,
                            duration: notification_duration.participant_joined,
                        });
                    }
                    break;
                case 'screenshare':
                    const screenShareParticipant = meeting.participants.joined
                        .toArray()
                        .filter((participant) => participant.screenShareEnabled)
                        .find((participant) => participant.id == activeTab.id);
                    if (screenShareParticipant != undefined) {
                        this.add({
                            id: 'spotlight',
                            message: `Now watching ${screenShareParticipant.name}'s screen`,
                            duration: notification_duration.webinar,
                        });
                    }
                    break;
            }
        };
        this.peerStageStatusListener = (participant) => {
            if (participant.stageStatus === 'REQUESTED_TO_JOIN_STAGE') {
                this.add({
                    id: `stage-request-${participant.id}`,
                    message: `${participant.name} ${this.t('notifications.requested_to_join_stage')}`,
                    duration: notification_duration.webinar,
                    button: {
                        text: this.t('notifications.accept'),
                        variant: 'primary',
                        onClick: async () => {
                            await this.meeting.stage.grantAccess([participant.userId]);
                            this.remove(`stage-request-${participant.id}`);
                        },
                    },
                });
                if (notification_sounds.webinar) {
                    this.audio.play('joined');
                }
            }
            if (participant.stageStatus === 'ON_STAGE') {
                this.add({
                    id: `stage-joined-${participant.id}`,
                    message: `${participant.name} ${this.t('notifications.joined_stage')}`,
                    duration: notification_duration.webinar,
                });
                if (notification_sounds.webinar) {
                    this.audio.play('joined');
                }
            }
        };
        this.stageRequestAccepted = () => {
            this.add({
                id: 'stage-request-accepted',
                message: this.t('notifications.request_to_join_accepted'),
                duration: 3000,
            });
        };
        this.stageRequestRejected = () => {
            this.add({
                id: 'stage-request-rejected',
                message: this.t('notifications.request_to_join_rejected'),
                duration: 3000,
            });
        };
        this.newStageRequests = ({ count }) => {
            this.add({
                id: 'new-stage-request',
                message: `You have ${count < 0 ? 'new stage' : `${count} pending`} request${count === 1 ? '' : 's'}`,
                duration: 3000,
            });
        };
        this.stageStatusUpdateListener = (status) => {
            if (status === 'ON_STAGE')
                this.addStagePeersListeners(meeting);
            else
                this.removeStagePeersListeners(meeting);
        };
        !uiStore.showLivestream(meeting) && ((_a = meeting.chat) === null || _a === void 0 ? void 0 : _a.addListener('chatUpdate', this.chatUpdateListener));
        // temp fix for viewType mismatch with CHAT
        if (((_b = meeting.self.config.viewType) === null || _b === void 0 ? void 0 : _b.toString()) === 'CHAT') {
            return;
        }
        // all non Chat viewtype code from here
        const currentDevices = meeting.self.getCurrentDevices();
        if (currentDevices.speaker != null) {
            this.audio.setDevice(currentDevices.speaker.deviceId);
        }
        if (isLivestream)
            (_c = meeting.stage) === null || _c === void 0 ? void 0 : _c.on('stageStatusUpdate', this.stageStatusUpdateListener);
        else
            this.addStagePeersListeners(meeting);
        if (this.canAcceptWaitingRequests()) {
            meeting.participants.waitlisted.addListener('participantJoined', this.waitlistedParticipantJoinedListener);
            meeting.participants.waitlisted.addListener('participantLeft', this.waitlistedParticipantLeftListener);
        }
        (_d = meeting.polls) === null || _d === void 0 ? void 0 : _d.addListener('pollsUpdate', this.pollUpdateListener);
        meeting.self.addListener('deviceUpdate', this.deviceUpdateListener);
        meeting.meta.addListener('socketConnectionUpdate', this.socketConnectionUpdateListener);
        (_e = meeting.meta) === null || _e === void 0 ? void 0 : _e.addListener('activeTabUpdate', this.activeTabUpdateListener);
        (_f = meeting.recording) === null || _f === void 0 ? void 0 : _f.addListener('recordingUpdate', this.onRecordingUpdate);
        (_g = meeting.stage) === null || _g === void 0 ? void 0 : _g.addListener('stageRequestApproved', this.stageRequestAccepted);
        (_h = meeting.stage) === null || _h === void 0 ? void 0 : _h.addListener('stageRequestRejected', this.stageRequestRejected);
        if (meeting.self.permissions.stageEnabled && meeting.self.permissions.acceptStageRequests) {
            (_j = meeting.stage) === null || _j === void 0 ? void 0 : _j.addListener('newStageRequest', this.newStageRequests);
        }
    }
    configChanged(config) {
        if (config != null) {
            if ((config === null || config === void 0 ? void 0 : config.config) != null) {
                this.permissions = parseConfig(config.config);
                this.enabledSounds = getEnabledSounds(this.permissions.notification_sounds);
            }
        }
    }
    statesChanged(states) {
        var _a;
        if (states != null) {
            const notificationSoundsEnabled = !((_a = states === null || states === void 0 ? void 0 : states.prefs) === null || _a === void 0 ? void 0 : _a.muteNotificationSounds);
            // toggle only the notification sounds values which were enabled in the first place
            for (const permission of this.enabledSounds) {
                if (permission in this.permissions.notification_sounds) {
                    this.permissions.notification_sounds[permission] = notificationSoundsEnabled;
                }
            }
        }
    }
    apiErrorListener({ detail }) {
        const { trace, message } = detail;
        this.add({
            id: trace,
            message,
            duration: DEFAULT_NOTIFICATION_DURATION,
            icon: this.iconPack.warning,
        });
    }
    sendNotificationListener({ detail }) {
        const { trace, message } = detail;
        this.add({
            id: trace,
            message,
            duration: DEFAULT_NOTIFICATION_DURATION,
        });
    }
    add(notification) {
        // show notifications only if tab is in focus and a maximum of 5 at a time
        if (document.visibilityState === 'visible' && this.notifications.length < 5) {
            // adds new notification to start of array so they appear at the bottom
            this.notifications = [...this.notifications, notification];
        }
    }
    remove(id) {
        this.notifications = this.notifications.filter((notification) => notification.id !== id);
    }
    handleDismiss(e) {
        e.stopPropagation();
        const id = e.detail;
        const el = this.host.shadowRoot.querySelector(`[data-id="${id}"]`);
        // exit animation
        el === null || el === void 0 ? void 0 : el.classList.add('exit');
        setTimeout(() => {
            index$1.writeTask(() => {
                this.remove(id);
            });
        }, 400);
    }
    canPlayParticipantJoinedSound() {
        return (this.permissions.participant_joined_sound_notification_limit == undefined ||
            this.permissions.participant_joined_sound_notification_limit <= 0 ||
            this.meeting.participants.count <=
                this.permissions.participant_joined_sound_notification_limit);
    }
    canPlayChatSound() {
        return (this.permissions.participant_chat_message_sound_notification_limit == undefined ||
            this.permissions.participant_chat_message_sound_notification_limit <= 0 ||
            this.meeting.participants.count <=
                this.permissions.participant_chat_message_sound_notification_limit);
    }
    canAcceptWaitingRequests() {
        return (this.permissions.notifications.participant_joined_waitlist &&
            this.meeting.self.permissions.acceptWaitingRequests);
    }
    render() {
        if (!this.meeting) {
            return;
        }
        return (index$1.h(index$1.Host, null, index$1.h("div", { onMouseEnter: () => (this.paused = true), onFocusin: () => (this.paused = true), onMouseLeave: () => (this.paused = false), onFocusout: () => (this.paused = false) }, this.notifications.map((notification) => (index$1.h("rtk-notification", { size: this.size, key: notification.id, "data-id": notification.id, notification: notification, onRtkNotificationDismiss: (e) => this.handleDismiss(e), iconPack: this.iconPack, paused: this.paused, t: this.t }))))));
    }
    get host() { return index$1.getElement(this); }
    static get watchers() { return {
        "meeting": ["meetingChanged"],
        "config": ["configChanged"],
        "states": ["statesChanged"]
    }; }
};
__decorate([
    index.SyncWithStore()
], RtkNotifications.prototype, "meeting", void 0);
__decorate([
    index.SyncWithStore()
], RtkNotifications.prototype, "states", void 0);
__decorate([
    index.SyncWithStore()
], RtkNotifications.prototype, "config", void 0);
__decorate([
    index.SyncWithStore()
], RtkNotifications.prototype, "t", void 0);
__decorate([
    index.SyncWithStore()
], RtkNotifications.prototype, "iconPack", void 0);
RtkNotifications.style = RtkNotificationsStyle0;

exports.rtk_notifications = RtkNotifications;
