/* eslint-disable no-underscore-dangle */
import React, { useContext, useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { MediaRoomContext } from '../services/MediaRoomService';
import { MediaStates, setProducersState } from '../store/roomSlice';
import { GridManager } from '../components/video/GridManager';
import { useWindowDimensions, NativeModules, Platform, BackHandler } from 'react-native';
import ConfirmExitModal from '../components/ConfirmExitModal';
import { UserTrackContext } from '../services/UserTrackProvider';
import HostWaitingListModal from '../components/HostWaitlistManagerModal';
import analytics from '../utils/analytics';
import { ConfigServiceContext } from '../utils/ConfigProvider';
import useCopyClipboard, { useDisclosure } from '../utils/browser-utils';
import { Flex } from '../themes/components';
import StageHeader from '../components/StageHeader';
import StageControlBar from '../components/StageControlBar';
import RequestToJoinStageModal from '../components/RequestToJoinStageModal';
import StartPresentingModal from '../components/StartPresentingModal';
import PIPModeContainer from '../components/video/PIPModeContainer';
const { DyteHelper } = NativeModules;
export default function Stage(props) {
    const { mediaRoom, } = useContext(MediaRoomContext);
    const { mediaTracks: { audioTrack, webcamTrack, screenShareVideoTrack, }, } = useContext(UserTrackContext);
    const dispatch = useDispatch();
    const { isOpen, onClose, onOpen } = useDisclosure();
    const { roomName } = props;
    const { sessionConfig, meeting } = useContext(ConfigServiceContext);
    const roomDisplayTitle = useSelector((state) => state.room.roomDisplayTitle);
    const legacyMode = useSelector((state) => state.room.legacyMode);
    const joined = useSelector((state) => state.room.joined);
    const waitlistedPeers = useSelector((state) => state.room.waitlistedPeers);
    const producersState = useSelector((state) => state.room.producersState);
    const joinedPeers = useSelector((state) => state.peers.joinedPeers);
    const audioMuted = useSelector((state) => state.participant.audioMuted);
    const hiddenParticipant = useSelector((state) => state.participant.hidden);
    const webinarHiddenParticipant = useSelector((state) => state.participant.webinarHiddenParticipant);
    const plugins = useSelector((state) => state.plugin);
    const { isOpen: isSidebarOpen, onClose: onSidebarClose, onOpen: onSidebarOpen } = useDisclosure();
    const windowDimensions = useWindowDimensions();
    let { height, width } = sessionConfig.theme.dimensions || windowDimensions;
    const [gridOverlayComponent, setGridOverlayComponent] = useState(null);
    const [popupContents, setPopupContents] = useState(null);
    const [hasCopied, onCopy] = useCopyClipboard(`/stage/${roomName}`);
    useEffect(() => {
        // remove when ios native module for the same is implemented
        if (Platform.OS === 'android') {
            DyteHelper.activateScreenWake();
            return () => DyteHelper.deactivateScreenWake();
        }
        return () => { };
    });
    useEffect(() => {
        const changeTrack = async () => {
            if (legacyMode !== mediaRoom.legacyMode) {
                mediaRoom.legacyMode = legacyMode;
                mediaRoom.resetVideoProducers(webcamTrack, screenShareVideoTrack);
            }
        };
        if (mediaRoom && producersState === MediaStates.LOADED) {
            changeTrack();
        }
    }, [legacyMode, producersState]);
    useEffect(() => {
        if (meeting) {
            meeting.grid.setOverlay = (element, timeout) => {
                if (typeof element === 'string') {
                    /* setGridOverlayComponent(<div
                        dangerouslySetInnerHTML={{ __html: sessionConfig.waitingRoom.element }}
                    />); */
                }
                else {
                    setGridOverlayComponent(element);
                }
                if (timeout) {
                    setTimeout(() => {
                        setGridOverlayComponent(null);
                    }, timeout);
                }
            };
            meeting.createPopup = (element) => {
                setPopupContents(element);
            };
        }
    }, [meeting]);
    useEffect(() => {
        BackHandler.addEventListener('hardwareBackPress', () => {
            // If ConfirmExitModal is already open, exit 
            if (isOpen) {
                return false;
            }
            onOpen();
            return true;
        });
    }, []);
    useEffect(() => {
        const startProducing = async () => {
            dispatch(setProducersState(MediaStates.CONNECTING));
            if (webcamTrack) {
                await mediaRoom.shareWebcam(webcamTrack);
            }
            if (audioTrack) {
                await mediaRoom.shareMic(audioTrack, audioMuted);
            }
            dispatch(setProducersState(MediaStates.LOADED));
        };
        const fetchData = () => {
            mediaRoom.getMesssages();
            mediaRoom.getPolls();
        };
        if (producersState === MediaStates.NOT_STARTED) {
            analytics.captureEvent('stage started', { roomName, videoOn: webcamTrack !== undefined, audioOn: audioTrack !== undefined });
            // Don't fetch data again for hidden state change
            if (!mediaRoom.hidden) {
                fetchData();
            }
            mediaRoom.hidden = false;
            startProducing();
        }
    }, [producersState, joined]);
    const isMobile = width < 1024;
    let sidebarWidth = 380;
    if (width <= 1400) {
        sidebarWidth = 300;
    }
    const isLandscape = width > height;
    const mobileLandscape = isMobile && isLandscape;
    if (mobileLandscape) {
        [width, height] = [height, width];
    }
    const gridWidth = isSidebarOpen ? width - sidebarWidth : width;
    const middleComponentSize = height - (sessionConfig.theme.control_bar.is_enabled ? 64 : 0);
    const gridSize = middleComponentSize - (sessionConfig.theme.header.is_enabled ? 40 : 0);
    const transform = `rotate(${mobileLandscape ? -90 : 0}deg)`;
    const transformOrigin = `${Math.floor(width / 2)}px ${Math.floor(width / 2)}px`;
    /*
   const popup = (
        <TemplateModal
            isOpen={!!popupContents}
            onClose={() => setPopupContents(null)}
            copyrightNotice={false}
        >
            {popupContents}
        </TemplateModal>
    ); */
    return (<Flex direction="column" bg="secondary.1000" height={height} width={width}>
			<Flex direction="column" width={gridWidth} height={height}>
				
				<ConfirmExitModal isOpen={isOpen} onClose={onClose}/>
				<HostWaitingListModal isOpen={waitlistedPeers.length > 0} peers={waitlistedPeers}/>
				{sessionConfig.theme.header.is_enabled && (<StageHeader title={roomDisplayTitle !== '' ? roomDisplayTitle : roomName} linkCopied={hasCopied} copyLink={onCopy} isMobile={isMobile} width={width} height={height} noOfParticipants={joinedPeers.length}/>)}
				<PIPModeContainer isMobile={isMobile}/>
				<GridManager widthOffset={isSidebarOpen ? sidebarWidth : 0} singleSpeakerView={plugins.main.length > 0 && !isMobile}/>
				<RequestToJoinStageModal isMobile={isMobile}/>
				<StartPresentingModal isMobile={isMobile}/>
				{sessionConfig.theme.control_bar.is_enabled && (<StageControlBar linkCopied={hasCopied} copyLink={onCopy} isMobile={isMobile} leaveCall={onOpen}/>)}
			</Flex>
		</Flex>);
}
//# sourceMappingURL=Stage.js.map