/* eslint-disable no-underscore-dangle */
import React, { useContext, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Stage from '../pages/Stage';
import { MediaRoomContext, MediaRoomProvider } from '../services/MediaRoomService';
import { PluginServiceProvider } from '../services/PluginService';
import { WebSocketProvider } from '../services/MediaRoomSocketService';
import { MediaStates, resetRoom, setShowSetupScreen, WaitingState, } from '../store/roomSlice';
import { resetPeers } from '../store/peersSlice';
import LoadingScreen from '../components/LoadingScreen';
/* import WaitingRoom from '../pages/WaitingRoom';
 */ import { PeersProvider } from '../services/PeersService';
import { resetParticipant, setUserDisplayName, permissionEnum, } from '../store/participantSlice';
import { useManualQuery } from 'graphql-hooks';
import { useWindowDimensions, TextInput } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { ConfigServiceContext } from '../utils/ConfigProvider';
import { ThemeContext } from 'styled-components';
import SelfPreview from '../components/SelfPreview';
import { UserTrackContext } from '../services/UserTrackProvider';
import { Flex, Stack, Text, Button, Box, } from '../themes/components';
import { setupPermissions } from '../native/permissions';
import { SDK_BUILD } from "../env";
import { useOrientation } from '../utils/browser-utils';
import borderRadius from '../themes/foundations/borderRadius';
const SESSION = `
query Session($roomName: String!, $password: String) {
	session(roomName: $roomName, password: $password) {
	  title,
	  roomNodeLink,
	  roomName,
	  password
	}
  }
`;
export function JoinStage(props) {
    const { mediaRoom, } = useContext(MediaRoomContext);
    const displayName = useSelector((state) => state.participant.displayName);
    const audioMuted = useSelector((state) => state.participant.audioMuted);
    const routerState = useSelector((state) => state.room.routerState);
    const joined = useSelector((state) => state.room.joined);
    const waitingState = useSelector((state) => state.room.waitingState);
    const { roomName } = props;
    const { sessionConfig, meeting } = useContext(ConfigServiceContext);
    const windowDimensions = useWindowDimensions();
    const { height, width } = sessionConfig.theme.dimensions || windowDimensions;
    // console.log(routerState,MediaStates.LOADED);
    useEffect(() => {
        if (routerState === MediaStates.LOADED && mediaRoom) {
            mediaRoom.joinRoom(displayName, audioMuted);
        }
    }, [routerState]);
    useEffect(() => {
        if (waitingState === WaitingState.ACCEPTED && mediaRoom) {
            mediaRoom.joinRoom(displayName, audioMuted);
        }
    }, [waitingState]);
    useEffect(() => {
        if (joined && meeting) {
            meeting.emit(meeting.Events.meetingJoined);
        }
    }, [joined]);
    if (!joined) {
        return <LoadingScreen text="This seems to be taking too long..." showTextAfter={10}/>;
    }
    /* if (waitingState === WaitingState.WAITING) {
        return <WaitingRoom />;
    } */
    if (waitingState === WaitingState.REJECTED) {
        return (<Stack height={height} width={width} backgroundColor="#202124" justify="center" align="center">
				<Text color="textPrimary.100" className="dyte-client-noSelect">Host rejected you request</Text>
			</Stack>);
    }
    return <Stage roomName={roomName}/>;
}
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();
    let { 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 [inputError, setInputError] = React.useState({
        displayName: false,
        meetingCode: false,
    });
    const { orientation } = useOrientation();
    const isLandscape = orientation === "LANDSCAPE";
    if (isLandscape) {
        // [height,width] = [width,height];
    }
    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
        }
        // stats.setRoomName(roomName);
    }, []);
    /* useEffect(() => {
        if (presetFetched) {
            setupStreams();
        }
    }, [presetFetched]); */
    useEffect(() => {
        // uncomment in sdk builds
        if (meetingCode && (authToken || !SDK_BUILD)) {
            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 onJoinMeetingClicked = () => {
        const inputFieldsErrors = {
            displayName: false,
            meetingCode: false,
        };
        if (!meetingCode || !displayName) {
            if (!displayName) {
                inputFieldsErrors.displayName = true;
            }
            if (!meetingCode) {
                inputFieldsErrors.meetingCode = true;
            }
        }
        if (displayName && meetingCode) {
            dispatch(setShowSetupScreen(false));
            dispatch(resetRoom({ roomName: meetingCode }));
            getSession({ variables: { roomName: meetingCode, password: '' } });
            updatePreset(meetingCode, authToken);
        }
        setInputError(inputFieldsErrors);
    };
    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 (<Flex height={height} width={width} justify={isLandscape ? "space-evenly" : "center"} align="center" backgroundColor="secondary.1000" position="absolute" top={0} direction={isLandscape ? "row" : "column"} bottom={0}>
				<Box mb={20} width={width / (isLandscape ? 3 : 1) - 40}>
					
				</Box>
				<SelfPreview />
	
				<Flex width={width / (isLandscape ? 3 : 1) - 40} justify="center">
				<Text color="textPrimary.300" mt={20}>Name: </Text>
				<TextInput style={{
            paddingLeft: 15,
            height: 48,
            marginVertical: 10,
            borderRadius: borderRadius.medium,
            color: colors.textPrimary[300],
            backgroundColor: colors.secondary[800],
            width: width / (isLandscape ? 3 : 1) - 40,
        }} onChangeText={(e) => dispatch(setUserDisplayName(e))} editable={!SDK_BUILD} showSoftInputOnFocus={!SDK_BUILD} value={displayName}/>
				{inputError.displayName && <Text color="danger.300" mb={10}> Please enter your display name</Text>}
				{!roomName && !SDK_BUILD && (<Box>
						<Text color="textPrimary.300">Meeting Code:</Text>
						<TextInput style={{
            paddingLeft: 15,
            paddingBottom: 7,
            paddingTop: 7,
            marginVertical: 10,
            borderRadius: borderRadius.medium,
            color: colors.textPrimary[300],
            backgroundColor: colors.secondary[800],
            width: width / (isLandscape ? 3 : 1) - 40,
        }} onChangeText={onChangeMeetingCode} value={meetingCode}/>
						{inputError.meetingCode && <Text color="danger.300" mb={10}> Please enter meeting room code</Text>}
					</Box>)}
				<Button onClick={onJoinMeetingClicked}>
					<Box bg="primary.500" py={12} mt={10} borderRadius={borderRadius.medium} align="center">
						<Text>Join</Text>
					</Box>
				</Button>
				</Flex>
			</Flex>);
    }
    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=SDKSetupStage.js.map