/* eslint-disable no-underscore-dangle */
import React, { createContext, useContext, useEffect, useState, } from 'react';
import { batch, useDispatch } from 'react-redux';
import { store } from '../store/store';
import { JoinStageSettings, resetParticipant, setUser } from '../store/participantSlice';
import CustomThemeChakraProvider from '../themes/CustomThemeChakraProvider';
import config from '../utils/config';
import { setVisibilitySettings, updateCanPresent, updateWebinarPresentingSetting } from "../store/participantSlice";
import { resetRoom, setPresetFetched, setRoomGridView, setRoomViewType } from '../store/roomSlice';
import { resetPeers } from '../store/peersSlice';
import { ClientContext } from 'graphql-hooks';
import { decode as atob } from 'base-64';
import { convertPresetToV2, DyteViewTypes } from '../utils/dyte-utils/src';
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 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'));
        }
        meeting.config = { ...config };
        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 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) {
                let newConfig;
                const { preset } = userPresetResp.data;
                if (preset.hasOwnProperty('uiConfig') || preset.hasOwnProperty('role')) {
                    newConfig = convertPresetToV2(meeting.config, preset);
                    updateConfig({ ...newConfig });
                }
                else {
                    newConfig = preset;
                    updateConfig({ ...newConfig });
                }
                batch(() => {
                    dispatch(setPresetFetched(true));
                    if (newConfig.permissions?.view_type) {
                        dispatch(setRoomViewType(newConfig.permissions.view_type));
                    }
                    if (newConfig.permissions.view_type === DyteViewTypes.webinar) {
                        dispatch(updateWebinarPresentingSetting(true));
                        dispatch(updateCanPresent(newConfig.permissions.can_present));
                    }
                    else if (newConfig.permissions.hidden_participant) {
                        const visibilty = {
                            hidden: true,
                            joinStageSettings: JoinStageSettings.ALLOWED,
                        };
                        dispatch(setVisibilitySettings(visibilty));
                    }
                });
            }
        }
        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.connectionConfig.authToken) {
                client.setHeader('Authorization', `Bearer ${meeting.connectionConfig.authToken}`);
                saveUser(meeting.connectionConfig.authToken);
                setAuthToken(true);
            }
            else
                anonLogin();
            /*
            setSessionConfig({ ...defaultConfig });
            meeting._setUIConfig = (updateConfig);
            meeting._overlayHook = (peerId: string, element) => {
                sessionConfig.peerOverlays[peerId] = element;
                setSessionConfig({ ...sessionConfig });
            };
            meeting._controlsHook = (control) => {
                sessionConfig.participantControls.push(control);
            };
            if (meeting?.uiConfig) {
                merge(sessionConfig, meeting.uiConfig);
                setSessionConfig(sessionConfig);
            } */
        }
    }, [meeting]);
    useEffect(() => {
        if (meeting) {
            dispatch(resetRoom({}));
            dispatch(resetParticipant());
            dispatch(resetPeers());
        }
        else
            anonLogin();
    }, []);
    // const socketState = useSelector((state: RootState) => state.room.socketState);
    const context = {
        sessionConfig,
        meeting,
        updatePreset,
    };
    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