/* eslint-disable no-underscore-dangle */
import React, { createContext, useContext, useEffect, useState, } from 'react';
import { useWindowDimensions, } from 'react-native';
import { batch, useDispatch, useSelector } from 'react-redux';
import { store } from '../store/store';
import { JoinStageSettings, resetParticipant, setUser, setVisibilitySettings, updateCanPresent, updateWebinarPresentingSetting, } from '../store/participantSlice';
import CustomThemeChakraProvider from '../themes/CustomThemeChakraProvider';
import config from '../utils/config';
import merge from 'lodash.merge';
import { resetRoom, setPresetFetched, setRoomGridView, setRoomViewType, } from '../store/roomSlice';
import { peerMetadataUpdated, resetPeers, switchToWebinar } from '../store/peersSlice';
import { ClientContext } from 'graphql-hooks';
import { decode as atob } from 'base-64';
import { convertPresetToV2, DyteViewTypes, convertThemeToV2, } from '../utils/dyte-utils/src';
import { useOrientation } from '../utils/browser-utils';
export const ConfigServiceContext = createContext(null);
function parseJwt(token) {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(atob(base64).split('').map((c) => `%${(`00${c.charCodeAt(0).toString(16)}`).slice(-2)}`).join(''));
    return JSON.parse(jsonPayload);
}
export const ConfigServiceProvider = (props) => {
    const dispatch = useDispatch();
    const { children, meeting } = props;
    const [sessionConfig, setSessionConfig] = useState({ ...meeting.config });
    const [authToken, setAuthToken] = useState(null);
    const client = useContext(ClientContext);
    const { orientation } = useOrientation();
    const [participantControls, setParticipantControls] = useState([]);
    const peerId = useSelector((state) => state.participant.peerId);
    const isLandscape = orientation === 'LANDSCAPE';
    const windowDimensions = useWindowDimensions();
    const updateConfig = (config) => {
        const newConfig = { ...config };
        if (newConfig.theme?.grid?.defaultView?.toLowerCase() === 'multi') {
            store.dispatch(setRoomGridView('multi'));
        }
        else if (newConfig.theme.grid?.defaultView?.toLowerCase() === 'highlighted') {
            store.dispatch(setRoomGridView('highlighted'));
        }
        newConfig.theme = convertThemeToV2(newConfig.theme, meeting._uiConfig);
        meeting.config = newConfig;
        setSessionConfig({ ...config });
    };
    const saveUser = async (userAuthToken) => {
        const userDetailsReq = await fetch(`${config.apiBase}/auth/basicUserDetails?authToken=${userAuthToken}`, {
            method: 'GET',
            headers: {
                authorization: `Bearer ${userAuthToken}`,
            },
        });
        const userDetailsResp = await userDetailsReq.json();
        if (userDetailsResp.user) {
            if (userDetailsResp.user.email.endsWith('@anon.dyte.in')) {
                delete userDetailsResp.user.email;
                delete userDetailsResp.user.name;
            }
            client.setHeader('Authorization', `Bearer ${userAuthToken}`);
            dispatch(setUser({ ...userDetailsResp.user, authToken: userAuthToken }));
        }
    };
    const processPreset = async (preset) => {
        let newConfig;
        if (preset?.uiConfig || preset?.role) {
            newConfig = convertPresetToV2(meeting.config, preset);
        }
        else {
            newConfig = preset;
        }
        batch(() => {
            dispatch(setPresetFetched(true));
            dispatch(peerMetadataUpdated({
                id: peerId,
                view_type: newConfig.permissions?.view_type,
                preset_name: newConfig.preset_name,
            }));
            if (newConfig.permissions?.view_type) {
                dispatch(setRoomViewType(newConfig.permissions.view_type));
            }
            if (sessionConfig.permissions.view_type !== DyteViewTypes.webinar
                && newConfig.permissions.view_type === DyteViewTypes.webinar) {
                dispatch(updateWebinarPresentingSetting(true));
                dispatch(updateCanPresent(newConfig.permissions.can_present));
                dispatch(switchToWebinar());
            }
            else if (newConfig.permissions.hidden_participant) {
                const visibilty = {
                    hidden: true,
                    joinStageSettings: JoinStageSettings.ALLOWED,
                };
                dispatch(setVisibilitySettings(visibilty));
            }
        });
        updateConfig({ ...merge(meeting.config, newConfig) });
    };
    const updatePreset = async (roomName, authToken) => {
        try {
            const userPresetReq = await fetch(`${config.apiBase}/v1/userpreset`, {
                method: 'POST',
                headers: {
                    'content-type': 'application/json',
                },
                body: JSON.stringify({
                    authToken,
                    roomName,
                    version: '0.5.0',
                    clientType: 'CLIENT_APP',
                }),
            });
            const userPresetResp = await userPresetReq.json();
            if (userPresetResp?.data?.preset) {
                const { preset } = userPresetResp.data;
                processPreset(preset);
            }
        }
        catch (e) {
            // paass
            updateConfig(meeting.config);
        }
    };
    const anonLogin = () => {
        fetch(`${config.apiBase}/auth/anonymous`).then((resp) => resp.json()).then((resp) => {
            const { id } = parseJwt(resp.authToken);
            dispatch(setUser({ authToken: resp.authToken, id }));
            client.setHeader('Authorization', `Bearer ${resp.authToken}`);
            setAuthToken(true);
        });
    };
    useEffect(() => {
        if (meeting) {
            if (meeting.setupConfig.authToken) {
                client.setHeader('Authorization', `Bearer ${meeting.setupConfig.authToken}`);
                saveUser(meeting.setupConfig.authToken);
                setAuthToken(true);
            }
            else {
                anonLogin();
            }
            meeting._controlsHook = (control) => {
                setParticipantControls((p) => p.concat(control));
            };
        }
    }, [meeting]);
    useEffect(() => {
        const meetingDimensions = meeting.config?.theme?.dimensions || {};
        const { width, height } = meetingDimensions;
        if ((isLandscape && width < height) || (!isLandscape && height < width)) {
            meetingDimensions.width = height;
            meetingDimensions.height = width;
            updateConfig({ ...meeting.config });
        }
    }, [orientation]);
    useEffect(() => {
        if (meeting) {
            dispatch(resetRoom({}));
            dispatch(resetParticipant());
            dispatch(resetPeers());
        }
        else
            anonLogin();
    }, []);
    // const socketState = useSelector((state: RootState) => state.room.socketState);
    const context = {
        sessionConfig,
        meeting,
        updatePreset,
        processPreset,
        participantControls,
    };
    const absoluteOverlay = {
        zIndex: 1000, position: 'fixed', top: 0, left: 0,
    };
    if (!authToken)
        return <></>;
    return (<ConfigServiceContext.Provider value={context}>
			<CustomThemeChakraProvider>
				{children}
			</CustomThemeChakraProvider>
		</ConfigServiceContext.Provider>);
};
//# sourceMappingURL=ConfigProvider.js.map