import React, { useContext, useEffect, useRef, useState, } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { RoomSocketState, setCurrentPage } from '../../store/roomSlice';
import LoadingScreen from '../../components/LoadingScreen';
import MultiSpeakerGridLayout from '../../components/video/MultiSpeakerGridLayout';
import SingleSpeakerGridLayout from '../../components/video/SingleSpeakerGridLayout';
import { PeersServiceContext } from '../../services/PeersService';
import { ConfigServiceContext } from '../../utils/ConfigProvider';
import GestureRecognizer from 'react-native-swipe-gestures';
import { MediaRoomContext } from '../../services/MediaRoomService';
import { Spinner, Text, VStack } from '../../themes/components';
import { DyteViewTypes } from '../../utils/dyte-utils/src';
import { RequestToJoinType } from '../../store/participantSlice';
import { useWindowDimensions } from 'react-native';
import { OrientationContext } from '../../services/OrientationContext';
import { ThemeContext } from 'styled-components';
const WebinarAudioRoomsDefaultScreen = ({ roomViewType }) => {
    const { sessionConfig } = useContext(ConfigServiceContext);
    const attendee = !sessionConfig.permissions.can_present;
    const { colors } = useContext(ThemeContext);
    const { orientation } = React.useContext(OrientationContext);
    const mobileLandscape = orientation === 'LANDSCAPE';
    const windowDimensions = useWindowDimensions();
    // eslint-disable-next-line prefer-const
    let { height, width } = sessionConfig.theme.dimensions || windowDimensions;
    let heightOffset = 0;
    if (sessionConfig.theme.header.is_enabled) {
        heightOffset -= 72;
    }
    if (sessionConfig.theme.control_bar.is_enabled) {
        heightOffset -= 56;
    }
    // for mobile landscape, the parent grid height width are reverse, and rotated 90 degree,
    // but we want the video to not be rotated, so mobile width is subtracted with header, controlbar
    if (mobileLandscape) {
        width += heightOffset + 56;
    }
    else {
        height += heightOffset;
    }
    const webinarStartString = 'To begin the webinar please start presenting';
    const audioRoomStartString = 'To being Audio Room, Please Enable Audio';
    const prestingString = roomViewType === DyteViewTypes.audioRoom ? 'Host will start Audio Room Soon' : '	Host will start presenting soon';
    const toStartString = roomViewType === DyteViewTypes.audioRoom
        ? audioRoomStartString : webinarStartString;
    return (<VStack bg="secondary.1000" width={width} height={height} px={15} justifyContent="center" align="center">
			{attendee && (<>
					<Text fontSize={26} py={10} fontWeight="bold">
						{prestingString}
					</Text>
					<Spinner color={colors.textPrimary[100]} size="large"/>
				</>)}
			{!attendee && (<>
					<Text fontSize={26} py={10} fontWeight="bold">
						You are the host
					</Text>
					<Text fontSize={14}>
						{toStartString}
					</Text>
				</>)}
		</VStack>);
};
const filterPeerForCurrentPage = (
// processedPeers: ProcessedPeer[],
peerMap, currentPagePeerIds) => {
    const nextGrid = [];
    for (let i = 0; i < currentPagePeerIds.length; i += 1) {
        const peerId = currentPagePeerIds[i];
        if (peerMap.has(peerId)) {
            nextGrid.push(peerMap.get(peerId));
        }
    }
    return nextGrid;
};
const _GridManager = ({ widthOffset, singleSpeakerView = false, }) => {
    const { mediaRoom } = useContext(MediaRoomContext);
    const gridView = useSelector((state) => state.room.gridView);
    const plugins = useSelector((state) => state.plugin);
    const sharingScreen = useSelector((state) => state.participant.sharingScreen);
    const gridSetup = useRef([]);
    const maxPreferredStreams = useSelector((state) => state.room.maxPreferredStreams);
    const socketState = useSelector((state) => state.room.socketState);
    const currentPage = useSelector((state) => state.room.currentPage);
    const currentPagePeerIds = useSelector((state) => state.peers.currentPagePeerIds);
    const activeSpeakerPagePeerIds = useSelector((state) => state.peers.activeSpeakerPagePeerIds);
    const joinedPeers = useSelector((state) => state.peers.joinedPeers);
    const roomViewType = useSelector((state) => state.room.roomViewType);
    const { sessionConfig } = useContext(ConfigServiceContext);
    // + 1 because user using the app is also in the meeting
    // Divided by 6 because in single page there would be max 6 people
    const noOfPages = Math.ceil(((joinedPeers.length + 1) / 6));
    const dispatch = useDispatch();
    const { meeting } = useContext(ConfigServiceContext);
    const peersService = useContext(PeersServiceContext);
    const { processedPeers, screenshareVideoConsumer } = peersService;
    const { selfPeer } = peersService;
    const hiddenParticipant = useSelector((state) => state.participant.hidden);
    const webinarHiddenParticipant = useSelector((state) => state.participant.webinarHiddenParticipant) && roomViewType === DyteViewTypes.webinar;
    const [activePeer, setActivePeer] = useState(selfPeer);
    const filteredCurrentPagePeerIds = currentPagePeerIds; // .filter((e) => e !== selfPeer.id);
    useEffect(() => {
        if (socketState === RoomSocketState.NOT_STARTED) {
            meeting?.emit(meeting.Events.disconnect);
        }
    }, [socketState]);
    const updatePage = (pageNumber) => {
        // Page number 0 is active speaker grid
        if (pageNumber > -1 && pageNumber <= noOfPages) {
            dispatch(setCurrentPage(pageNumber));
            mediaRoom.getPage(pageNumber);
        }
    };
    let gridPeers = [];
    const peerMap = new Map();
    processedPeers.forEach((peer) => {
        peerMap.set(peer.id, peer);
    });
    if (!selfPeer) {
        return <LoadingScreen />;
    }
    if (filteredCurrentPagePeerIds.length > 0 && currentPage > 0) {
        peerMap.set(selfPeer.id, selfPeer);
        gridPeers = filterPeerForCurrentPage(peerMap, filteredCurrentPagePeerIds);
        gridSetup.current = gridPeers.map((p) => p.id);
    }
    else {
        gridPeers = filterPeerForCurrentPage(peerMap, activeSpeakerPagePeerIds);
        gridSetup.current = gridPeers.map((p) => p.id);
        gridPeers = gridPeers
            .concat((hiddenParticipant
            || (roomViewType === DyteViewTypes.webinar && webinarHiddenParticipant)
            || (!webinarHiddenParticipant
                && roomViewType === DyteViewTypes.webinar
                && selfPeer.requestToJoinType === RequestToJoinType.ask)) ? [] : [selfPeer]);
    }
    if (socketState === RoomSocketState.NOT_STARTED) {
        return <LoadingScreen inStage text="You got disconnected! Retrying connection..."/>;
    }
    if (gridPeers.length < 1) {
        if (roomViewType === DyteViewTypes.webinar) {
            return <WebinarAudioRoomsDefaultScreen roomViewType={DyteViewTypes.webinar}/>;
        }
        return <LoadingScreen loading text="Please wait for the meeting to be started" inStage/>;
    }
    // if (roomViewType === DyteViewTypes.webinar) {
    // 	const processedPeersSize = (hiddenParticipant || webinarHiddenParticipant
    // 		|| (!webinarHiddenParticipant && selfPeer.requestToJoinType === RequestToJoinType.ask))
    // 		? processedPeers.length : processedPeers.length + 1;
    // 	gridSize = processedPeersSize >= maxPreferredStreams
    // 		? maxPreferredStreams : processedPeersSize;
    // } else {
    // 	gridSize = gridPeers.filter((p) => !p.hiddenParticipant).length;
    // }
    if (screenshareVideoConsumer
        || singleSpeakerView
        || sharingScreen
        || gridView === 'highlighted'
        || plugins.main.length > 0) {
        return (<SingleSpeakerGridLayout peers={gridPeers} sharingScreen={sharingScreen} widthOffset={widthOffset}/>);
    }
    return (<GestureRecognizer onSwipeLeft={(state) => updatePage(currentPage + 1)} onSwipeRight={(state) => updatePage(currentPage - 1)} style={{
        flex: 1,
    }}>
			<MultiSpeakerGridLayout peers={gridPeers} widthOffset={widthOffset}/>
		</GestureRecognizer>);
};
_GridManager.defaultProps = {
    singleSpeakerView: false,
};
export const GridManager = React.memo(_GridManager);
//# sourceMappingURL=GridManager.js.map