import { r as registerInstance, d as createEvent, h, a as Host } from './index-55463a54.js';
import { e as defaultIconPack, i as useLanguage } from './ui-store-76bb0e8e.js';
import { S as SyncWithStore } from './index-dafb4b7f.js';

const rtkScreenShareToggleCss = ":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{display:block}:host([data-hidden]){display:none}";
const RtkScreenShareToggleStyle0 = rtkScreenShareToggleCss;

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;
};
const deviceCanScreenShare = () => {
    return (typeof navigator !== 'undefined' &&
        typeof navigator.mediaDevices !== 'undefined' &&
        'getDisplayMedia' in navigator.mediaDevices);
};
const RtkScreenShareToggle = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.stateUpdate = createEvent(this, "rtkStateUpdate", 7);
        this.apiError = createEvent(this, "rtkApiError", 7);
        /** Variant */
        this.variant = 'button';
        /** Icon pack */
        this.iconPack = defaultIconPack;
        /** Language */
        this.t = useLanguage();
        /**
         * Maximum screen share count (value from preset)
         * -1 denotes there is no limit on maximum
         */
        this.maxScreenShareCount = -1;
        this.screenShareCount = 0;
        this.screenShareEnabled = false;
        this.canScreenShare = false;
        this.shareScreenPermission = 'NOT_REQUESTED';
        this.screenShareState = {
            tooltipLabel: this.t('screenshare.start'),
            label: this.t('screenshare.start'),
            icon: this.iconPack.share_screen_start,
            classList: {},
            showWarning: false,
            disable: false,
        };
        this.stageStatus = 'OFF_STAGE';
        this.screenShareListener = () => {
            const activeScreenShares = this.meeting.participants.active
                .toArray()
                .filter((p) => p.screenShareEnabled).length;
            const selfScreenShare = this.meeting.self.screenShareEnabled ? 1 : 0;
            this.screenShareCount = activeScreenShares + selfScreenShare;
            this.screenShareEnabled = this.meeting.self.screenShareEnabled;
            this.getState();
            this.meeting.__internals__.logger.info('rtkScreenShare::screenShareUpdate', {
                media: {
                    screenshare: {
                        enabled: this.screenShareEnabled,
                        count: this.screenShareCount,
                    },
                },
            });
        };
        this.participantLeftListener = ({ screenShareEnabled }) => {
            if (screenShareEnabled) {
                // decrement count if participant who left had screenShareEnabled
                // and don't let it go below 0 (just a failsafe)
                this.screenShareCount = Math.max(this.screenShareCount - 1, 0);
                this.getState();
                this.meeting.__internals__.logger.info('rtkScreenShare::screenShareUpdate', {
                    media: {
                        screenshare: {
                            enabled: this.screenShareEnabled,
                            count: this.screenShareCount,
                        },
                    },
                });
            }
        };
        this.stageStatusListener = () => {
            this.stageStatus = this.meeting.stage.status;
            this.canScreenShare = this.meeting.self.permissions.canProduceScreenshare === 'ALLOWED';
        };
        this.mediaPermissionUpdateListener = ({ kind, message }) => {
            if (kind === 'screenshare') {
                this.shareScreenPermission = message;
                this.getState();
                if (message === 'COULD_NOT_START') {
                    this.apiError.emit({
                        trace: this.t('screenshare.permissions'),
                        message: this.t('screenshare.error.unknown'),
                    });
                }
                if (this.hasPermissionError()) {
                    const permissionModalSettings = {
                        enabled: true,
                        kind: 'screenshare',
                    };
                    this.stateUpdate.emit({ activePermissionsMessage: permissionModalSettings });
                }
            }
        };
        this.reachedMaxScreenShares = () => {
            // checks if a limit exists, and if limit is reached
            return this.maxScreenShareCount > 0 && this.screenShareCount >= this.maxScreenShareCount;
        };
        this.toggleScreenShare = async () => {
            var _a;
            if (this.screenShareState.disable)
                return;
            if (this.hasPermissionError()) {
                const permissionModalSettings = {
                    enabled: true,
                    kind: 'screenshare',
                };
                this.stateUpdate.emit({ activePermissionsMessage: permissionModalSettings });
                return false;
            }
            const self = (_a = this.meeting) === null || _a === void 0 ? void 0 : _a.self;
            if (this.screenShareEnabled) {
                self.disableScreenShare();
                return;
            }
            if (self == null ||
                !this.canScreenShare ||
                this.reachedMaxScreenShares() ||
                this.hasPermissionError())
                return;
            this.screenShareState = Object.assign(Object.assign({}, this.screenShareState), { disable: true });
            await self.enableScreenShare();
            this.screenShareState = Object.assign(Object.assign({}, this.screenShareState), { disable: false });
            this.stateUpdate.emit({ activeMoreMenu: false });
        };
    }
    connectedCallback() {
        if (!deviceCanScreenShare()) {
            this.meeting.__internals__.logger.error('[rtk-screenshare-toggle] Device does not support screensharing.');
            return;
        }
        this.meetingChanged(this.meeting);
    }
    disconnectedCallback() {
        var _a, _b, _c, _d, _e, _f;
        (_a = this.meeting) === null || _a === void 0 ? void 0 : _a.participants.joined.removeListener('screenShareUpdate', this.screenShareListener);
        (_b = this.meeting) === null || _b === void 0 ? void 0 : _b.participants.joined.removeListener('participantLeft', this.participantLeftListener);
        (_c = this.meeting) === null || _c === void 0 ? void 0 : _c.self.removeListener('screenShareUpdate', this.screenShareListener);
        (_d = this.meeting) === null || _d === void 0 ? void 0 : _d.self.removeListener('mediaPermissionUpdate', this.mediaPermissionUpdateListener);
        (_f = (_e = this.meeting) === null || _e === void 0 ? void 0 : _e.stage) === null || _f === void 0 ? void 0 : _f.removeListener('stageStatusUpdate', this.stageStatusListener);
    }
    meetingChanged(meeting) {
        if (meeting != null) {
            const { self, stage } = meeting;
            this.canScreenShare = this.meeting.self.permissions.canProduceScreenshare === 'ALLOWED';
            this.maxScreenShareCount = self.config.maxScreenShareCount;
            this.screenShareEnabled = self.screenShareEnabled;
            let screenShareCount = 0;
            for (const participant of meeting.participants.joined.toArray()) {
                if (participant.screenShareEnabled) {
                    screenShareCount++;
                }
            }
            this.screenShareCount = screenShareCount;
            this.getState();
            meeting.__internals__.logger.info('rtkScreenShare::initialise', {
                media: {
                    screenshare: {
                        enabled: this.screenShareEnabled,
                        count: this.screenShareCount,
                        maxAllowedCount: this.maxScreenShareCount,
                    },
                },
            });
            this.stageStatus = meeting.stage.status;
            meeting.participants.joined.addListener('screenShareUpdate', this.screenShareListener);
            meeting.participants.joined.addListener('participantLeft', this.participantLeftListener);
            self.addListener('screenShareUpdate', this.screenShareListener);
            self.addListener('mediaPermissionUpdate', this.mediaPermissionUpdateListener);
            stage === null || stage === void 0 ? void 0 : stage.addListener('stageStatusUpdate', this.stageStatusListener);
        }
    }
    hasPermissionError() {
        return (this.shareScreenPermission === 'SYSTEM_DENIED' || this.shareScreenPermission === 'DENIED');
    }
    getState() {
        let tooltipLabel = '';
        let label = '';
        let icon = '';
        let classList = {};
        const hasError = this.hasPermissionError() && !this.screenShareEnabled;
        const limitReached = this.reachedMaxScreenShares() && !this.screenShareEnabled;
        const couldNotStart = this.shareScreenPermission === 'COULD_NOT_START';
        if (this.screenShareEnabled && !hasError) {
            label = this.t('screenshare.stop');
            icon = this.iconPack.share_screen_stop;
            classList['red-icon'] = true;
        }
        else {
            label = this.t('screenshare.start');
            icon = this.iconPack.share_screen_start;
        }
        if (this.shareScreenPermission === 'SYSTEM_DENIED') {
            tooltipLabel = this.t('perm_sys_denied.screenshare');
            classList['red-icon'] = true;
        }
        else if (this.shareScreenPermission === 'DENIED') {
            tooltipLabel = this.t('perm_denied.screenshare');
            classList['red-icon'] = true;
        }
        else {
            tooltipLabel = label;
        }
        if (limitReached) {
            tooltipLabel = this.t('screenshare.error.max_count');
        }
        if (couldNotStart) {
            tooltipLabel = this.t('screenshare.error.unknown');
        }
        this.screenShareState = {
            tooltipLabel,
            label,
            icon,
            classList,
            disable: hasError || limitReached,
            showWarning: hasError || limitReached || couldNotStart,
        };
    }
    render() {
        if (!deviceCanScreenShare() ||
            !this.canScreenShare ||
            ['OFF_STAGE', 'REQUESTED_TO_JOIN_STAGE'].includes(this.stageStatus)) {
            return h(Host, { "data-hidden": true });
        }
        return (h(Host, { title: this.screenShareState.label }, h("rtk-tooltip", { placement: "top", kind: "block", label: this.screenShareState.tooltipLabel, delay: 600, part: "tooltip" }, h("rtk-controlbar-button", { part: "controlbar-button", size: this.size, iconPack: this.iconPack, variant: this.variant, label: this.screenShareState.label, icon: this.screenShareState.icon, class: this.screenShareState.classList, onClick: this.toggleScreenShare, disabled: this.screenShareState.disable, showWarning: this.screenShareState.showWarning }))));
    }
    static get watchers() { return {
        "meeting": ["meetingChanged"]
    }; }
};
__decorate([
    SyncWithStore()
], RtkScreenShareToggle.prototype, "states", void 0);
__decorate([
    SyncWithStore()
], RtkScreenShareToggle.prototype, "meeting", void 0);
__decorate([
    SyncWithStore()
], RtkScreenShareToggle.prototype, "iconPack", void 0);
__decorate([
    SyncWithStore()
], RtkScreenShareToggle.prototype, "t", void 0);
RtkScreenShareToggle.style = RtkScreenShareToggleStyle0;

export { RtkScreenShareToggle as rtk_screen_share_toggle };
