/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable no-underscore-dangle */
import React, { useContext, useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { nanoid } from '@reduxjs/toolkit';
import { Platform, useWindowDimensions, NativeModules } from 'react-native';
import { initiatePresenting, permissionEnum, PresentingState, requestedJoinToStageState, RequestToJoinStageState, RequestToJoinType, requestToJoinType, } from '../store/participantSlice';
import { Icon, Box, Flex, Spinner, } from '../themes/components';
import borderRadius from '../themes/foundations/borderRadius';
import { useDisclosure, withAnchorPoint, } from '../utils/browser-utils';
import { getScreenShare } from '../utils/media-utils';
import { setRoomGridView, setScreenShareRequested, } from '../store/roomSlice';
import { MediaRoomContext } from '../services/MediaRoomService';
import { StageControlButton, MakeMenu } from '../components/StageControlButton';
import { UserTrackContext } from '../services/UserTrackProvider';
import DropFromStage from '../components/Modals/DropFromStage';
/* import { StageSidebarView } from '../components/StageSidebar';
import { PeersServiceContext } from '../services/PeersService';
/* import MuteAllPopover from '../components/MuteAllPopover';
 */ import { MessageTypes } from '../types/APITypes';
import analytics from '../utils/analytics';
import { ConfigServiceContext } from '../utils/ConfigProvider';
import MobileDrawer from '../components/MobileDrawer';
import { PeersServiceContext } from '../services/PeersService';
import MobileChatTab from '../components/StageSidebar/MobileChatTab';
import PollsTab from '../components/StageSidebar/PollsTab';
import ParticipantsTab from '../components/StageSidebar/ParticipantsTab';
import { DYTE_DEV_MODE } from '../env';
import { WebinarAcceptRequestType } from '../types/newTypes';
import { DyteViewTypes } from '../utils/dyte-utils/src';
import { ThemeContext } from 'styled-components';
import { getActiveRecording, startRecording, stopRecording } from '../utils/recording';
import NotificationCircle from '../components/notificationCircle';
import { DrawerContext } from '../services/DrawerService';
import { OrientationContext } from '../services/OrientationContext';
const { DyteHelper } = NativeModules;
const _StageControlBar = ({ leaveCall, copyLink, linkCopied, isMobile, }) => {
    const { mediaRoom } = useContext(MediaRoomContext);
    const { isOpen, onOpen, onClose } = useDisclosure();
    const { selfPeer, allMuted } = useContext(PeersServiceContext);
    const red = 'danger.500';
    const gray = 'textPrimary.400';
    const disabledGray = 'secondary.700';
    const { mediaTracks: { screenShareVideoTrack, setScreenShareVideoTrack, screenShareAudioTrack, setScreenShareAudioTrack, audioTrack, }, inputDevices: { toggleAudioState, toggleVideoState, audioInputDevices, videoInputDevices, onAudioInputChange, onVideoInputChange, }, audioButtonsEnabled, videoButtonsEnabled, } = useContext(UserTrackContext);
    const { meeting, sessionConfig } = useContext(ConfigServiceContext);
    const windowDimensions = useWindowDimensions();
    let { height, width } = sessionConfig.theme.dimensions || windowDimensions;
    const { audio: audioAllowed, screenshare: screensShareAllowed } = sessionConfig
        .permissions.produce;
    const { drawerExpanded, setDrawerExpander, openedTab, setopenedTab, } = React.useContext(DrawerContext);
    const consumers = useSelector((state) => state.consumers.activeConsumers);
    const audioMuted = useSelector((state) => state.participant.audioMuted);
    const videoOff = useSelector((state) => state.participant.videoOff);
    const videoTrackSelection = useSelector((state) => state.participant.videoTrackSelection);
    const audioTrackSelection = useSelector((state) => state.participant.audioTrackSelection);
    const plugins = useSelector((state) => state.plugin.plugins);
    const sharingScreen = useSelector((state) => state.participant.sharingScreen);
    const permissions = useSelector((state) => state.participant.participantPermissions);
    const chatMessages = useSelector((state) => state.room.chatMessages);
    const requestToJoinPeersList = useSelector((state) => state.room.requestToJoinPeersList);
    const newParticipantRequest = (requestToJoinPeersList || []).filter((m) => m.seen !== true);
    const selfRequestToJoinType = useSelector((state) => state.participant.requestToJoinType);
    const joinToStageState = useSelector((state) => state.participant.requestToJoinStageState);
    const canPresent = useSelector((state) => state.participant.canPresent);
    const roomViewType = useSelector((state) => state.room.roomViewType);
    const videoAllowed = roomViewType !== DyteViewTypes.webinar
        ? sessionConfig.permissions.produce.video.allow : canPresent;
    const webinarHiddenParticipant = useSelector((state) => state.participant.webinarHiddenParticipant) && roomViewType === DyteViewTypes.webinar;
    const gridView = useSelector((state) => state.room.gridView);
    const presentingState = useSelector((state) => state.participant.presentingState);
    const [extraButtons, setExtraButtons] = useState([]);
    const [showDropFromStageModal, setShowDropFromState] = useState(false);
    useEffect(() => {
        if (meeting) {
            meeting.controlBar._setButtons = (customButtons) => {
                setExtraButtons([...customButtons]);
            };
        }
    }, [meeting]);
    useEffect(() => {
        if (sessionConfig.permissions.view_type === DyteViewTypes.groupCall) {
            // if in PIP mode, remove from stage in group call
            if (joinToStageState === RequestToJoinStageState.ACCEPTED) {
                mediaRoom.removePeerFromStage(mediaRoom.peerid, WebinarAcceptRequestType.REQUESTED_BY_PARTICIPANT);
            }
        }
        if (sessionConfig.permissions.view_type === DyteViewTypes.webinar) {
            if (webinarHiddenParticipant && !videoOff) {
                toggleVideoState();
            }
        }
    }, [sessionConfig.permissions.view_type]);
    const dispatch = useDispatch();
    const { orientation, orientationType } = React.useContext(OrientationContext);
    const mobileLandscape = orientation === 'LANDSCAPE';
    // TODO: This is wrong. fix get transform logic
    if (mobileLandscape) {
        [height, width] = [width, height];
    }
    const getTransform = () => {
        const x = { transform: [{ rotate: '-90deg' }] };
        return withAnchorPoint(x, { x: 1, y: 0 }, { width, height: 64 });
    };
    const landscapeRight = orientationType === 'landscapeLeft' ? 56 : height - 6;
    const mobileLandscapeProps = mobileLandscape ? {
        zIndex: 10, position: 'absolute', top: 0, right: landscapeRight, ...getTransform(),
    }
        : { position: 'absolute', bottom: 1 };
    const screenShareHandler = async () => {
        if (!sharingScreen) {
            analytics.captureEvent('share screen started');
            if (screenShareVideoTrack !== undefined) {
                screenShareVideoTrack.stop();
            }
            if (screenShareAudioTrack !== undefined) {
                screenShareVideoTrack.stop();
            }
            if (Platform.Version >= 26) {
                await DyteHelper.createNotificationChannel();
            }
            dispatch(setScreenShareRequested(true));
            await DyteHelper.startService();
            try {
                const tracks = await getScreenShare();
                if (!videoOff)
                    toggleVideoState(); // if(!videoOff)toggleVideoState();
                setScreenShareVideoTrack(tracks.video);
                setScreenShareAudioTrack(tracks.audio);
                mediaRoom.shareScreen(tracks);
            }
            catch (error) {
                if (error?.message !== 'NotAllowedError') {
                    console.error(error);
                }
                dispatch(setScreenShareRequested(true));
            }
        }
        else {
            dispatch(setScreenShareRequested(false));
            mediaRoom.disableScreenShare();
            setScreenShareVideoTrack(undefined);
            setScreenShareAudioTrack(undefined);
            DyteHelper.stopService();
        }
    };
    const changeGridView = async () => {
        if (gridView === 'multi')
            dispatch(setRoomGridView('highlighted'));
        else
            dispatch(setRoomGridView('multi'));
    };
    const processLabel = (dev) => {
        if (!dev.label)
            return dev.label;
        if (Number.isInteger(Number(dev.label))) {
            return dev.facing === 'environment'
                ? 'Back Camera'
                : 'Front Camera';
        }
        return dev.label;
    };
    const selfId = useSelector((state) => state.participant.id);
    const unReadChatMessages = chatMessages.filter((m) => m.read !== true
        && m.userId !== selfId && m.type !== MessageTypes.poll);
    const unSeenPolls = chatMessages.filter((m) => m.read !== true
        && m.type === MessageTypes.poll
        && m.userId !== selfId);
    const unReadNotificationsLength = unReadChatMessages.length
        + unSeenPolls.length + newParticipantRequest.length;
    const { colors } = useContext(ThemeContext);
    const screenShareCount = consumers.filter((c) => c.kind === 'video' && c.appData.screenShare).length;
    const [recordingId, setRecordingId] = useState(null);
    const [recordingState, setRecordingState] = useState('not_init');
    const recordingPeer = useSelector((state) => state.peers.recordingPeer);
    const authToken = useSelector((state) => state.participant.authToken);
    const roomName = useSelector((state) => state.room.roomName);
    const organizationId = useSelector((state) => state.participant.organizationId);
    useEffect(() => {
        if (authToken && roomName && organizationId && recordingState === 'not_init') {
            const options = { authToken, roomName, organizationId };
            getActiveRecording(options).then((resp) => {
                if (resp.data && resp.data.recording) {
                    if (resp.data.recording.status === 'UPLOADING') {
                        setRecordingState('stopping');
                    }
                    else if (resp.data.recording.status === 'INVOKED') {
                        setRecordingState('starting');
                    }
                    else {
                        setRecordingState('recording');
                    }
                    setRecordingId(resp.data.recording.id);
                }
                else {
                    setRecordingState('not_started');
                }
            });
        }
    }, [authToken, roomName, organizationId, recordingId]);
    useEffect(() => {
        if (recordingState === 'starting' && recordingPeer) {
            setRecordingState('recording');
        }
        else if (recordingState === 'stopping' && !recordingPeer) {
            setRecordingState('not_started');
        }
    }, [recordingPeer]);
    const onRecordButtonClicked = async () => {
        const options = { authToken, roomName, organizationId };
        if (recordingId) {
            setRecordingState('stopping');
            options.recordingId = recordingId;
            try {
                await stopRecording(options);
                setRecordingId(null);
            }
            catch (err) {
                setRecordingState('recording');
            }
        }
        else {
            setRecordingState('starting');
            try {
                const resp = await startRecording(options);
                const id = resp.data?.recording?.id;
                setRecordingId(id);
            }
            catch (err) {
                setRecordingState('not_started');
            }
        }
    };
    const recordingLoading = recordingState === 'starting'
        || recordingState === 'stopping' || recordingState === 'not_init';
    const getRecordingLabel = () => {
        switch (recordingState) {
            case 'not_init':
                return 'Loading';
            case 'not_started':
                return 'Record';
            case 'recording':
                return 'Stop Record';
            case 'starting':
                return 'Starting Recording';
            case 'stopping':
                return 'Stopping Recording';
            default:
                return 'Loading';
        }
    };
    const getRecordingIcon = () => {
        switch (recordingState) {
            case 'not_started':
                return <Icon name="fiber-manual-record" fill={red}/>;
            case 'recording':
                return <Icon name="fiber-manual-record" fill={gray}/>;
            case 'starting':
            case 'stopping':
            case 'not_init':
            default:
                return <Spinner color={colors.textPrimary[100]} size="small"/>;
        }
    };
    const getPermissionMessage = (deviceType, permission, devices) => {
        let message = '';
        if (permission === permissionEnum.DENIED) {
            message = `${deviceType} permission denied. To enable please click on the lock icon besides the addresss bar.`;
        }
        else if (devices.length === 0) {
            message = `No ${deviceType} devices found.`;
        }
        else if (permission === permissionEnum.FAILED)
            message = `Error occured in getting ${deviceType}.`;
        return message;
    };
    const screenshareButton = [sessionConfig.theme.control_bar.elements.screenshare
            && sessionConfig.permissions.produce.screenshare
            && selfRequestToJoinType !== RequestToJoinType.ask
            && DYTE_DEV_MODE ? {
            icon: sharingScreen
                ? 'stop-screen-share'
                : 'screen-share',
            label: sharingScreen ? 'Stop Sharing' : 'Share Screen',
            onClick: screenShareHandler,
            disabled: !screensShareAllowed,
        } : {}];
    const chatButton = [sessionConfig.theme.control_bar.elements.chat ? {
            icon: 'chat',
            label: 'Chat',
            mainComponent: <MobileChatTab />,
            disabled: false,
        } : {}];
    const pollButton = [sessionConfig.theme.control_bar.elements.polls ? {
            icon: 'poll',
            label: 'Polls',
            mainComponent: <PollsTab />,
            disabled: false,
        } : {}];
    const participantsButton = [sessionConfig.theme.control_bar.elements.participants ? {
            icon: 'groups',
            label: 'Participants',
            mainComponent: <ParticipantsTab />,
            disabled: false,
        } : {}];
    const recordingButton = [sessionConfig.permissions?.can_record ? {
            disabled: recordingLoading,
            onClick: onRecordButtonClicked,
            icon: getRecordingIcon(),
            label: getRecordingLabel(),
        } : {}];
    const muteAllButton = [sessionConfig.permissions?.can_allow_participant_audio ? {
            icon: 'voice-off',
            label: 'Mute all',
            disabled: false,
            drawerComponent: (<MakeMenu menu={[
                {
                    title: 'Mute all',
                    options: [{
                            key: 'mute-video',
                            value: 'video',
                            children: 'Mute Video',
                        },
                        {
                            key: 'mute-audio',
                            value: 'audio',
                            children: 'Mute Audio',
                        },
                    ],
                    defaultValue: null,
                    onChange: (value) => {
                        if (value === 'video') {
                            mediaRoom.muteAllVideo();
                        }
                        if (value === 'audio') {
                            mediaRoom.muteAll(true);
                        }
                        setDrawerExpander(false);
                        setopenedTab(null);
                    },
                },
            ]}/>),
        } : {}];
    const handleRequestToJoin = (selectedOption) => {
        if (joinToStageState === RequestToJoinStageState.ACCEPTED) {
            setShowDropFromState(true);
        }
        else {
            dispatch(requestedJoinToStageState(RequestToJoinStageState.INITIATED));
            dispatch(requestToJoinType(selectedOption.value));
        }
    };
    const handlePresentAction = () => {
        if (webinarHiddenParticipant) {
            dispatch(initiatePresenting());
        }
        else {
            setShowDropFromState(true);
        }
    };
    const renderStageControlExpandBtn = () => {
        if ((mobileLandscape && Platform.OS === 'ios'))
            return null;
        return (<StageControlButton onClick={() => {
            setDrawerExpander(!drawerExpanded);
            /* setDrawerState(!isDrawerOpen); */
        }} icon={(<Flex>
						<Icon boxSize={24} name={drawerExpanded
            ? 'expand-more'
            : 'expand-less'} fill={gray}/>
						<Box position="absolute" top={-5} zIndex={25} right={-5}>
							{unReadNotificationsLength !== 0 && <NotificationCircle color={colors.primary['500']} number={unReadNotificationsLength}/>}
						</Box>
					</Flex>)} variant="primaryDefault" label="More"/>);
    };
    // If roomview type is meeting, hide drop from state modal
    useEffect(() => {
        if (roomViewType !== DyteViewTypes.webinar && showDropFromStageModal) {
            setShowDropFromState(false);
        }
    }, [roomViewType]);
    const handleRequestToJoinButtonColor = () => {
        if (joinToStageState === RequestToJoinStageState.ACCEPTED)
            return red;
        if (joinToStageState === RequestToJoinStageState.WAITING)
            return disabledGray;
        return gray;
    };
    return (<Box height={54} width={width} {...mobileLandscapeProps} alignSelf="flex-start" justify="flex-start" pt={3} bg="secondary.1000">
			<Flex justify="center" direction="row">
				<Flex direction="row" borderRadius={borderRadius.medium} bg="secondary.800">
					{mobileLandscape && renderStageControlExpandBtn()}
					{roomViewType === DyteViewTypes.webinar
        && ((sessionConfig.permissions?.can_present)
            || (sessionConfig.permissions?.request_produce
                && joinToStageState === RequestToJoinStageState.ACCEPTED
                && presentingState === PresentingState.NOT_PRESENTING))
        && (<StageControlButton onClick={handlePresentAction} icon={(<Icon boxSize={24} name={webinarHiddenParticipant
            ? 'present-to-all' : 'cancel-presentation'} fill={webinarHiddenParticipant ? 'green' : 'red'}/>)} label={webinarHiddenParticipant ? 'Present' : 'Stop'}/>)}
					{sessionConfig.permissions?.request_produce
        && (<StageControlButton onClick={handleRequestToJoin} icon={(<Icon boxSize={24} name={joinToStageState === RequestToJoinStageState.ACCEPTED
            ? 'cancel-presentation' : 'pan-tool'} fill={handleRequestToJoinButtonColor()}/>)} 
        /* fullMenu={joinToStageState !== RequestToJoinStageState.ACCEPTED}
        fullMenuOptions={sessionConfig.permissions?.request_produce
            && sessionConfig.theme?.pip_mode ? [{
                key: RequestToJoinType.present,
                value: RequestToJoinType.present,
                label: 'Request to Present',
            }, {
                key: RequestToJoinType.ask,
                value: RequestToJoinType.ask,
                label: 'Ask a question',
            }] : [{
                key: RequestToJoinType.present,
                value: RequestToJoinType.present,
                label: 'Request to Present',
            }]} */
        disabled={joinToStageState === RequestToJoinStageState.WAITING} label={joinToStageState === RequestToJoinStageState.ACCEPTED ? 'Drop' : 'Request'}/>)}
					{!webinarHiddenParticipant
        && (<>
								<StageControlButton disabled={!audioButtonsEnabled} onClick={toggleAudioState} icon={!audioMuted && selfPeer?.audioTrack ? (<Icon name="mic" fill={gray} boxSize={24}/>) : (<Icon name="mic-off" fill={!audioButtonsEnabled ? 'secondary.700' : red} boxSize={24}/>)} label={!audioMuted && audioTrack ? 'Mic On' : 'Mic Off'} ariaLabel="mute-toggle" menu={audioInputDevices.length > 0
            ? [
                {
                    title: 'Input Microphone Device',
                    options: audioInputDevices.map((dev, index) => ({
                        children: dev.label
                            || `Input ${index + 1}`,
                        key: dev.deviceId || nanoid(),
                        value: dev.deviceId,
                    })),
                    defaultValue: audioTrackSelection?.selectedDeviceId,
                    onChange: onAudioInputChange,
                },
            ]
            : []}/>

								<StageControlButton disabled={!videoButtonsEnabled} onClick={toggleVideoState} icon={videoOff ? (<Icon name="videocam-off" fill={!videoButtonsEnabled ? 'secondary.700' : red} boxSize={24}/>) : (<Icon name="videocam" fill={gray} boxSize={24}/>)} label={!videoOff ? 'Video On' : 'Video Off'} ariaLabel="camera-toggle" menu={videoInputDevices.length > 0
            ? [
                {
                    title: 'Camera Device',
                    options: videoInputDevices.map((dev, index) => ({
                        children: (<>
																	{dev.label
                            || `Camera ${index + 1}`}
																</>),
                        key: dev.deviceId || nanoid(),
                        value: dev.deviceId,
                    })),
                    defaultValue: videoTrackSelection?.selectedDeviceId,
                    onChange: onVideoInputChange,
                },
            ]
            : []}/>
							</>)}
					{sessionConfig.theme.control_bar.elements.chat
        && (<StageControlButton onClick={() => {
            setDrawerExpander(true);
            setopenedTab('chat');
        }} icon={(<Flex>
											<Icon boxSize={24} name="chat" fill={gray}/>
											{unReadChatMessages && unReadChatMessages.length > 0
            && (<Box position="absolute" top={-8} zIndex={25} right={unReadChatMessages.length > 9 ? -10 : -6}>
									<NotificationCircle color={colors.primary['500']} number={unReadNotificationsLength}/>
								</Box>)}
										</Flex>)} label="chat"/>)}
					<StageControlButton onClick={leaveCall} icon={<Icon name="call-end" fill={red} boxSize={24}/>} label="Leave"/>
					{!mobileLandscape
        && renderStageControlExpandBtn()}
				</Flex>
				{drawerExpanded && (<MobileDrawer unReadChatMessages={unReadChatMessages} unSeenPolls={unSeenPolls} webinarUnseenRequest={newParticipantRequest} options={[
        {
            icon: 'mic-external-on',
            label: 'Audio',
            disabled: false,
            drawerComponent: (<MakeMenu menu={audioInputDevices.length > 0
                ? [
                    {
                        title: 'Audio Device',
                        options: audioInputDevices.map((dev, index) => ({
                            children: dev.label
                                || `Input ${index + 1}`,
                            key: dev.deviceId
                                || nanoid(),
                            value: dev.deviceId,
                        })),
                        defaultValue: audioTrackSelection?.selectedDeviceId,
                        onChange: onAudioInputChange,
                    },
                ]
                : []}/>),
        },
        {
            icon: 'flip-camera-ios',
            label: 'Camera',
            disabled: !videoAllowed,
            drawerComponent: (<MakeMenu menu={videoInputDevices.length > 0
                ? [
                    {
                        title: 'Camera Device',
                        options: videoInputDevices.map((dev, index) => ({
                            children: processLabel(dev),
                            key: dev.deviceId
                                || nanoid(),
                            value: dev.deviceId,
                        })),
                        defaultValue: videoTrackSelection?.selectedDeviceId,
                        onChange: onVideoInputChange,
                    },
                ]
                : []}/>),
        },
        ...chatButton,
        ...pollButton,
        ...participantsButton,
        ...screenshareButton,
        ...recordingButton,
        ...muteAllButton,
    ].concat(extraButtons)
        .filter((el) => !(Platform.OS === 'ios' && el.icon === 'screen-share') && Object.keys(el).length !== 0).map((el) => ({ ...el, id: el.label.split(' ').join('-').toLowerCase() }))}/>)}
			</Flex>
			<DropFromStage onClose={() => setShowDropFromState(false)} isOpen={showDropFromStageModal}/>
		</Box>);
};
export default React.memo(_StageControlBar);
//# sourceMappingURL=StageControlBar.js.map