"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GridManager = void 0;
const react_1 = __importStar(require("react"));
const react_redux_1 = require("react-redux");
const roomSlice_1 = require("../../store/roomSlice");
const LoadingScreen_1 = __importDefault(require("../LoadingScreen"));
const MultiSpeakerGridLayout_1 = __importDefault(require("./MultiSpeakerGridLayout"));
const SingleSpeakerGridLayout_1 = __importDefault(require("./SingleSpeakerGridLayout"));
const PeersService_1 = require("../../services/PeersService");
const ConfigProvider_1 = require("../../utils/ConfigProvider");
const react_native_swipe_gestures_1 = __importDefault(require("react-native-swipe-gestures"));
const MediaRoomService_1 = require("../../services/MediaRoomService");
const components_1 = require("../../themes/components");
const src_1 = require("../../utils/dyte-utils/src");
const participantSlice_1 = require("../../store/participantSlice");
const react_native_1 = require("react-native");
const OrientationContext_1 = require("../../services/OrientationContext");
const styled_components_1 = require("styled-components");
const WebinarAudioRoomsDefaultScreen = ({ roomViewType, }) => {
    const { sessionConfig } = react_1.useContext(ConfigProvider_1.ConfigServiceContext);
    const attendee = !sessionConfig.permissions.can_present;
    const { colors } = react_1.useContext(styled_components_1.ThemeContext);
    const { orientation } = react_1.default.useContext(OrientationContext_1.OrientationContext);
    const mobileLandscape = orientation === 'LANDSCAPE';
    const windowDimensions = react_native_1.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 === src_1.DyteViewTypes.audioRoom
        ? 'Host will start Audio Room Soon'
        : '	Host will start presenting soon';
    const toStartString = roomViewType === src_1.DyteViewTypes.audioRoom
        ? audioRoomStartString
        : webinarStartString;
    return (react_1.default.createElement(components_1.VStack, { bg: "secondary.1000", width: width, height: height, px: 15, justifyContent: "center", align: "center" },
        attendee && (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement(components_1.Text, { fontSize: 26, py: 10, fontWeight: "bold" }, prestingString),
            react_1.default.createElement(components_1.Spinner, { color: colors.textPrimary[100], size: "large" }))),
        !attendee && (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement(components_1.Text, { fontSize: 26, py: 10, fontWeight: "bold" }, "You are the host"),
            react_1.default.createElement(components_1.Text, { fontSize: 14 }, toStartString)))));
};
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 } = react_1.useContext(MediaRoomService_1.MediaRoomContext);
    const gridView = react_redux_1.useSelector((state) => state.room.gridView);
    const plugins = react_redux_1.useSelector((state) => state.plugin);
    const sharingScreen = react_redux_1.useSelector((state) => state.participant.sharingScreen);
    const gridSetup = react_1.useRef([]);
    const maxPreferredStreams = react_redux_1.useSelector((state) => state.room.maxPreferredStreams);
    const socketState = react_redux_1.useSelector((state) => state.room.socketState);
    const currentPage = react_redux_1.useSelector((state) => state.room.currentPage);
    const currentPagePeerIds = react_redux_1.useSelector((state) => state.peers.currentPagePeerIds);
    const activeSpeakerPagePeerIds = react_redux_1.useSelector((state) => state.peers.activeSpeakerPagePeerIds);
    const joinedPeers = react_redux_1.useSelector((state) => state.peers.joinedPeers);
    const roomViewType = react_redux_1.useSelector((state) => state.room.roomViewType);
    const { sessionConfig } = react_1.useContext(ConfigProvider_1.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 = react_redux_1.useDispatch();
    const { meeting } = react_1.useContext(ConfigProvider_1.ConfigServiceContext);
    const peersService = react_1.useContext(PeersService_1.PeersServiceContext);
    const { processedPeers, screenshareVideoConsumer } = peersService;
    const { selfPeer } = peersService;
    const hiddenParticipant = react_redux_1.useSelector((state) => state.participant.hidden);
    const webinarHiddenParticipant = react_redux_1.useSelector((state) => state.participant.webinarHiddenParticipant) && roomViewType === src_1.DyteViewTypes.webinar;
    const [activePeer, setActivePeer] = react_1.useState(selfPeer);
    const filteredCurrentPagePeerIds = currentPagePeerIds; // .filter((e) => e !== selfPeer.id);
    react_1.useEffect(() => {
        if (socketState === roomSlice_1.RoomSocketState.NOT_STARTED) {
            meeting === null || meeting === void 0 ? void 0 : meeting.emit(meeting.Events.disconnect);
        }
    }, [socketState]);
    const updatePage = (pageNumber) => {
        // Page number 0 is active speaker grid
        if (pageNumber > -1 && pageNumber <= noOfPages) {
            dispatch(roomSlice_1.setCurrentPage(pageNumber));
            mediaRoom.getPage(pageNumber);
        }
    };
    let gridPeers = [];
    const peerMap = new Map();
    processedPeers.forEach((peer) => {
        peerMap.set(peer.id, peer);
    });
    if (!selfPeer) {
        return react_1.default.createElement(LoadingScreen_1.default, null);
    }
    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 === src_1.DyteViewTypes.webinar &&
                webinarHiddenParticipant) ||
            (!webinarHiddenParticipant &&
                roomViewType === src_1.DyteViewTypes.webinar &&
                selfPeer.requestToJoinType === participantSlice_1.RequestToJoinType.ask)
            ? []
            : [selfPeer]);
    }
    if (socketState === roomSlice_1.RoomSocketState.NOT_STARTED) {
        return (react_1.default.createElement(LoadingScreen_1.default, { inStage: true, text: "You got disconnected! Retrying connection..." }));
    }
    if (gridPeers.length < 1) {
        if (roomViewType === src_1.DyteViewTypes.webinar) {
            return (react_1.default.createElement(WebinarAudioRoomsDefaultScreen, { roomViewType: src_1.DyteViewTypes.webinar }));
        }
        return (react_1.default.createElement(LoadingScreen_1.default, { loading: true, text: "Please wait for the meeting to be started", inStage: true }));
    }
    // 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 (react_1.default.createElement(SingleSpeakerGridLayout_1.default, { peers: gridPeers, sharingScreen: sharingScreen, widthOffset: widthOffset }));
    }
    return (react_1.default.createElement(react_native_swipe_gestures_1.default, { onSwipeLeft: (state) => updatePage(currentPage + 1), onSwipeRight: (state) => updatePage(currentPage - 1), style: {
            flex: 1,
        } },
        react_1.default.createElement(MultiSpeakerGridLayout_1.default, { peers: gridPeers, widthOffset: widthOffset })));
};
_GridManager.defaultProps = {
    singleSpeakerView: false,
};
exports.GridManager = react_1.default.memo(_GridManager);
//# sourceMappingURL=GridManager.js.map