"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 });
/* eslint-disable no-underscore-dangle */
const react_1 = __importStar(require("react"));
const react_redux_1 = require("react-redux");
const MediaRoomService_1 = require("../../services/MediaRoomService");
const PluginService_1 = require("../../services/PluginService");
const MediaRoomSocketService_1 = require("../../services/MediaRoomSocketService");
const roomSlice_1 = require("../../store/roomSlice");
const peersSlice_1 = require("../../store/peersSlice");
const LoadingScreen_1 = __importDefault(require("../../components/LoadingScreen"));
/* import WaitingRoom from '@src/pages/WaitingRoom';
 */ const PeersService_1 = require("../../services/PeersService");
const participantSlice_1 = require("../../store/participantSlice");
const graphql_hooks_1 = require("graphql-hooks");
const browser_utils_1 = require("../../utils/browser-utils");
// import AsyncStorage from '@react-native-async-storage/async-storage';
const ConfigProvider_1 = require("../../utils/ConfigProvider");
const styled_components_1 = require("styled-components");
const UserTrackProvider_1 = require("../../services/UserTrackProvider");
const components_1 = require("../../themes/components");
const permissions_1 = require("../../consolidatedLibraries/permissions");
const env_1 = require("../../env");
const OrientationContext_1 = require("../../services/OrientationContext");
const borderRadius_1 = __importDefault(require("../../themes/foundations/borderRadius"));
const JoinStage_1 = __importDefault(require("./JoinStage"));
const showSetupScreen_1 = __importDefault(require("./showSetupScreen"));
const config_1 = __importStar(require("../../utils/config"));
const buffer_1 = require("buffer");
const decodeBase64 = (data) => buffer_1.Buffer.from(data, 'base64').toString('ascii');
const SESSION = `
query Session($roomName: String!, $password: String) {
	session(roomName: $roomName, password: $password) {
	  title,
	  roomNodeLink,
	  roomName,
	  password
	}
  }
`;
function SetupStage(props) {
    var _a, _b;
    const dispatch = react_redux_1.useDispatch();
    const { roomName, autoTune } = props;
    const peerId = react_redux_1.useSelector((state) => state.participant.peerId);
    const { meeting, sessionConfig, updatePreset } = react_1.useContext(ConfigProvider_1.ConfigServiceContext);
    const { colors } = react_1.useContext(styled_components_1.ThemeContext);
    const [issueId, setIssueId] = react_1.useState('');
    const [getSession, { data, error, loading }] = graphql_hooks_1.useManualQuery(SESSION, { variables: { roomName, password: '' } });
    const windowDimensions = browser_utils_1.useWindowDimensions();
    const { height, width } = sessionConfig.theme.dimensions || windowDimensions;
    const [permissionsFetched, setPermissionsFetched] = react_1.default.useState(false);
    const [roomNodeLink, setRoomNodeLink] = react_1.useState(null);
    const { setupStreams } = react_1.useContext(UserTrackProvider_1.UserTrackContext);
    const authToken = react_redux_1.useSelector((state) => state.participant.authToken);
    const displayName = react_redux_1.useSelector((state) => state.participant.displayName);
    const permissions = react_redux_1.useSelector((state) => state.participant.participantPermissions);
    const { audio: audioAllowed } = sessionConfig.permissions.produce;
    const videoConfig = sessionConfig.permissions.produce.video;
    const videoAllowed = videoConfig.allow;
    const showSetupScreen = react_redux_1.useSelector((state) => state.room.showSetupScreen);
    const [meetingCode, onChangeMeetingCode] = react_1.default.useState(roomName);
    const { orientation } = react_1.default.useContext(OrientationContext_1.OrientationContext);
    const isLandscape = orientation === 'LANDSCAPE';
    const roomViewType = react_redux_1.useSelector((state) => state.room.roomViewType);
    const { permissions_fetched } = sessionConfig;
    react_1.useEffect(() => {
        // TODO: What happens in case when presets are switched dynamically?
        // TODO: How does it work in case of webinar
        if (permissions_fetched) {
            if (videoAllowed) {
                // Fetch Audio and video
                permissions_1.setupPermissions(['camera', 'microphone']);
            }
            else if (audioAllowed) {
                permissions_1.setupPermissions(['microphone']);
            }
            else {
                // Fetch required Permissions only
                permissions_1.setupPermissions([]);
            }
            setPermissionsFetched(true);
        }
    }, [roomViewType, permissions_fetched]);
    react_1.useEffect(() => {
        dispatch(roomSlice_1.resetRoom({ roomName }));
        dispatch(peersSlice_1.resetPeers());
        // try {
        // 	AsyncStorage.getItem('dyte-display-name').then((name) => {
        // 		if (name !== null) {
        // 			dispatch(setUserDisplayName(name));
        // 		}
        // 	});
        // } catch (e) {
        // 	// saving error
        // }
    }, []);
    react_1.useEffect(() => {
        const isV2 = config_1.isV2AuthToken(authToken);
        // uncomment in sdk builds
        if (meetingCode && (authToken || env_1.DYTE_DEV_MODE) && !isV2) {
            dispatch(roomSlice_1.resetRoom({ roomName: meetingCode }));
            getSession({ variables: { roomName: meetingCode, password: '' } });
            updatePreset(meetingCode, authToken);
            // We get auth token from here
        }
        else if (isV2) {
            fetch(`${config_1.default.apiBase}/v2/internals/rooms`, {
                method: 'POST',
                headers: {
                    authorization: `Bearer ${authToken}`,
                },
            }).then((r) => r.json()).then((r) => {
                setRoomNodeLink(r.data.room_node_link);
            });
        }
    }, [meetingCode, authToken]);
    react_1.useEffect(() => {
        if (error) {
            if (error.graphQLErrors[0].message.indexOf('No open session') >= 0) {
                meeting === null || meeting === void 0 ? void 0 : meeting._onError('MEETING_NOTFOUND');
                setIssueId('MEETING_NOTFOUND');
            }
            else {
                try {
                    const errorData = error.graphQLErrors[0];
                    setIssueId(errorData === null || errorData === void 0 ? void 0 : errorData.message);
                }
                catch (_a) {
                    setIssueId('UNKNOWN');
                }
            }
        }
    }, [error, meeting]);
    react_1.useEffect(() => {
        if (permissions.camera !== participantSlice_1.permissionEnum.INIT ||
            permissions.microphone !== participantSlice_1.permissionEnum.INIT) {
            setupStreams();
        }
    }, [permissions.camera, permissions.microphone]);
    const joinMeeting = () => {
        const isV2 = config_1.isV2AuthToken(authToken);
        if (displayName && meetingCode && !isV2) {
            dispatch(roomSlice_1.setShowSetupScreen(false));
            dispatch(roomSlice_1.resetRoom({ roomName: meetingCode }));
            getSession({ variables: { roomName: meetingCode, password: '' } });
            updatePreset(meetingCode, authToken);
        }
        else if (isV2) {
            const { meetingId } = JSON.parse(decodeBase64(authToken.split('.')[1]));
            dispatch(roomSlice_1.setShowSetupScreen(false));
            dispatch(roomSlice_1.resetRoom({ roomName: meetingId }));
            // getSession({variables: {roomName: meetingId, password: ''}});
            updatePreset(meetingId, authToken);
        }
    };
    if (permissions.bluetooth === participantSlice_1.permissionEnum.INIT) {
        return react_1.default.createElement(LoadingScreen_1.default, { text: "Waiting for permissions..." });
    }
    const showMeetingJoinScreen = () => {
        setTimeout(() => {
            dispatch(peersSlice_1.resetPeers());
            dispatch(participantSlice_1.resetParticipant());
            dispatch(roomSlice_1.setShowSetupScreen(true));
            onChangeMeetingCode('');
            setIssueId('');
        });
    };
    if ((meeting === null || meeting === void 0 ? void 0 : meeting.showSetupScreen) &&
        (showSetupScreen === null || showSetupScreen === true)) {
        return (react_1.default.createElement(showSetupScreen_1.default, { width: width, height: height, isLandscape: isLandscape, meetingCode: meetingCode, roomName: roomName, onChangeMeetingCode: onChangeMeetingCode, joinMeeting: joinMeeting, title: (_a = data === null || data === void 0 ? void 0 : data.session) === null || _a === void 0 ? void 0 : _a.title }));
    }
    if (error) {
        return (react_1.default.createElement(LoadingScreen_1.default, { errorText: `Some error occured. Issue code: ${issueId}`, childComponents: react_1.default.createElement(components_1.Button, { onClick: showMeetingJoinScreen },
                react_1.default.createElement(components_1.Box, { bg: "primary.500", py: 15, px: 10, mt: 10, borderRadius: borderRadius_1.default.medium, align: "center" },
                    react_1.default.createElement(components_1.Text, null, "Try Again"))) }));
    }
    if (loading) {
        return react_1.default.createElement(LoadingScreen_1.default, { text: "Loading..." });
    }
    return (react_1.default.createElement(MediaRoomSocketService_1.WebSocketProvider, { url: config_1.isV2AuthToken(authToken) ? roomNodeLink : (_b = data === null || data === void 0 ? void 0 : data.session) === null || _b === void 0 ? void 0 : _b.roomNodeLink, roomURL: meetingCode, peerId: peerId },
        react_1.default.createElement(MediaRoomService_1.MediaRoomProvider, { peerId: peerId, roomName: meetingCode, autoTune: autoTune },
            react_1.default.createElement(PeersService_1.PeersProvider, null,
                react_1.default.createElement(PluginService_1.PluginServiceProvider, { roomName: meetingCode, peerId: peerId },
                    react_1.default.createElement(JoinStage_1.default, { roomName: meetingCode }))))));
}
SetupStage.defaultProps = {
    autoTune: true,
};
exports.default = SetupStage;
//# sourceMappingURL=index.js.map