/* eslint-disable no-underscore-dangle */
import React, { useContext, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { MediaRoomProvider } from '../../services/MediaRoomService';
import { PluginServiceProvider } from '../../services/PluginService';
import { WebSocketProvider } from '../../services/MediaRoomSocketService';
import { resetRoom, setShowSetupScreen } from '../../store/roomSlice';
import { resetPeers } from '../../store/peersSlice';
import LoadingScreen from '../../components/LoadingScreen';
/* import WaitingRoom from '@src/pages/WaitingRoom';
 */ import { PeersProvider } from '../../services/PeersService';
import { resetParticipant, setUserDisplayName, permissionEnum, } from '../../store/participantSlice';
import { useManualQuery } from 'graphql-hooks';
import { useWindowDimensions, } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { ConfigServiceContext } from '../../utils/ConfigProvider';
import { ThemeContext } from 'styled-components';
import { UserTrackContext } from '../../services/UserTrackProvider';
import { Text, Button, Box, } from '../../themes/components';
import { setupPermissions } from '../../consolidatedLibraries/permissions';
import { DYTE_DEV_MODE } from '../../env';
import { OrientationContext } from '../../services/OrientationContext';
import borderRadius from '../../themes/foundations/borderRadius';
import JoinStage from '../../pages/SDKSetupStage/JoinStage';
import ShowSetupScreen from '../../pages/SDKSetupStage/showSetupScreen';
const SESSION = `
query Session($roomName: String!, $password: String) {
	session(roomName: $roomName, password: $password) {
	  title,
	  roomNodeLink,
	  roomName,
	  password
	}
  }
`;
function SetupStage(props) {
    const dispatch = useDispatch();
    const { roomName, autoTune } = props;
    const peerId = useSelector((state) => state.participant.peerId);
    const { meeting, sessionConfig, updatePreset } = useContext(ConfigServiceContext);
    const { colors } = useContext(ThemeContext);
    const [issueId, setIssueId] = useState('');
    const [getSession, { data, error, loading }] = useManualQuery(SESSION, { variables: { roomName, password: '' } });
    const windowDimensions = useWindowDimensions();
    const { height, width } = sessionConfig.theme.dimensions || windowDimensions;
    const { setupStreams } = useContext(UserTrackContext);
    const authToken = useSelector((state) => state.participant.authToken);
    const displayName = useSelector((state) => state.participant.displayName);
    const presetFetched = useSelector((state) => state.room.presetFetched);
    const permissions = useSelector((state) => state.participant.participantPermissions);
    const showSetupScreen = useSelector((state) => state.room.showSetupScreen);
    const [meetingCode, onChangeMeetingCode] = React.useState(roomName);
    const { orientation } = React.useContext(OrientationContext);
    const isLandscape = orientation === 'LANDSCAPE';
    useEffect(() => {
        dispatch(resetRoom({ roomName }));
        dispatch(resetPeers());
        try {
            AsyncStorage.getItem('dyte-display-name').then((name) => {
                if (name !== null) {
                    dispatch(setUserDisplayName(name));
                }
            });
            setupPermissions();
        }
        catch (e) {
            // saving error
        }
    }, []);
    useEffect(() => {
        // uncomment in sdk builds
        if (meetingCode && (authToken || DYTE_DEV_MODE)) {
            dispatch(resetRoom({ roomName: meetingCode }));
            getSession({ variables: { roomName: meetingCode, password: '' } });
            updatePreset(meetingCode, authToken);
        }
    }, [meetingCode, authToken]);
    useEffect(() => {
        if (error) {
            if (error.graphQLErrors[0].message.indexOf('No open session') >= 0) {
                meeting?._onError('MEETING_NOTFOUND');
                setIssueId('MEETING_NOTFOUND');
            }
            else {
                try {
                    const errorData = error.graphQLErrors[0];
                    setIssueId(errorData?.message);
                }
                catch {
                    setIssueId('UNKNOWN');
                }
            }
        }
    }, [error, meeting]);
    useEffect(() => {
        if (permissions.camera !== permissionEnum.INIT
            && permissions.microphone !== permissionEnum.INIT) {
            setupStreams();
        }
    }, [permissions.camera, permissions.microphone]);
    const joinMeeting = () => {
        if (displayName && meetingCode) {
            dispatch(setShowSetupScreen(false));
            dispatch(resetRoom({ roomName: meetingCode }));
            getSession({ variables: { roomName: meetingCode, password: '' } });
            updatePreset(meetingCode, authToken);
        }
    };
    if (permissions.camera === permissionEnum.INIT
        || permissions.microphone === permissionEnum.INIT) {
        return <LoadingScreen text="Waiting for permissions..."/>;
    }
    const showMeetingJoinScreen = () => {
        setTimeout(() => {
            dispatch(resetPeers());
            dispatch(resetParticipant());
            dispatch(setShowSetupScreen(true));
            onChangeMeetingCode('');
            setIssueId('');
        });
    };
    if (meeting?.showSetupScreen && (showSetupScreen === null || showSetupScreen === true)) {
        return (<ShowSetupScreen width={width} height={height} isLandscape={isLandscape} meetingCode={meetingCode} roomName={roomName} onChangeMeetingCode={onChangeMeetingCode} joinMeeting={joinMeeting} title={data?.session?.title}/>);
    }
    if (error) {
        return (<LoadingScreen errorText={`Some error occured. Issue code: ${issueId}`} childComponents={(<Button onClick={showMeetingJoinScreen}>
						<Box bg="primary.500" py={15} px={10} mt={10} borderRadius={borderRadius.medium} align="center">
							<Text>Try Again</Text>
						</Box>
					</Button>)}/>);
    }
    if (loading) {
        return <LoadingScreen text="Loading..."/>;
    }
    return (<WebSocketProvider url={data?.session?.roomNodeLink} roomURL={meetingCode} peerId={peerId}>
			<MediaRoomProvider peerId={peerId} roomName={meetingCode} autoTune={autoTune}>
				<PeersProvider>
					<PluginServiceProvider roomName={meetingCode} peerId={peerId}>
						
						<JoinStage roomName={meetingCode}/>
					</PluginServiceProvider>
				</PeersProvider>
			</MediaRoomProvider>
		</WebSocketProvider>);
}
SetupStage.defaultProps = {
    autoTune: true,
};
export default SetupStage;
//# sourceMappingURL=index.js.map