"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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigServiceProvider = exports.ConfigServiceContext = void 0;
/* eslint-disable no-underscore-dangle */
const react_1 = __importStar(require("react"));
const react_native_1 = require("react-native");
const react_redux_1 = require("react-redux");
const store_1 = require("../store/store");
const participantSlice_1 = require("../store/participantSlice");
const CustomThemeChakraProvider_1 = __importDefault(require("../themes/CustomThemeChakraProvider"));
const config_1 = __importStar(require("./config"));
const lodash_merge_1 = __importDefault(require("lodash.merge"));
const roomSlice_1 = require("../store/roomSlice");
const peersSlice_1 = require("../store/peersSlice");
const graphql_hooks_1 = require("graphql-hooks");
const base_64_1 = require("base-64");
const src_1 = require("./dyte-utils/src");
const OrientationContext_1 = require("../services/OrientationContext");
const logger_1 = __importStar(require("./logger"));
const utils_1 = require("@dyteinternals/utils");
exports.ConfigServiceContext = react_1.createContext(null);
function parseJwt(token) {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(base_64_1.decode(base64)
        .split('')
        .map((c) => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`)
        .join(''));
    return JSON.parse(jsonPayload);
}
const ConfigServiceProvider = (props) => {
    const dispatch = react_redux_1.useDispatch();
    const { children, meeting } = props;
    const [sessionConfig, setSessionConfig] = react_1.useState(Object.assign(Object.assign({}, meeting.config), { permissions_fetched: false }));
    const [authToken, setAuthToken] = react_1.useState(null);
    const client = react_1.useContext(graphql_hooks_1.ClientContext);
    const { orientation } = react_1.default.useContext(OrientationContext_1.OrientationContext);
    const [participantControls, setParticipantControls] = react_1.useState([]);
    const peerId = react_redux_1.useSelector((state) => state.participant.peerId);
    const isLandscape = orientation === 'LANDSCAPE';
    const windowDimensions = react_native_1.useWindowDimensions();
    const updateConfig = (config) => {
        var _a, _b, _c, _d, _e, _f;
        const newConfig = Object.assign(Object.assign({}, config), { permissions_fetched: true });
        if ((_c = (_b = (_a = newConfig.theme) === null || _a === void 0 ? void 0 : _a.grid) === null || _b === void 0 ? void 0 : _b.defaultView) === null || _c === void 0 ? void 0 : _c.toLowerCase()) {
            store_1.store.dispatch(roomSlice_1.setRoomGridView((_f = (_e = (_d = newConfig.theme) === null || _d === void 0 ? void 0 : _d.grid) === null || _e === void 0 ? void 0 : _e.defaultView) === null || _f === void 0 ? void 0 : _f.toLowerCase()));
        }
        newConfig.theme = src_1.convertThemeToV2(newConfig.theme, meeting._uiConfig);
        meeting.config = newConfig;
        setSessionConfig(Object.assign({}, newConfig));
    };
    const saveUser = (userAuthToken) => __awaiter(void 0, void 0, void 0, function* () {
        const userDetailsReq = yield fetch(`${config_1.default.apiBase}/auth/basicUserDetails?authToken=${userAuthToken}`, {
            method: 'GET',
            headers: {
                authorization: `Bearer ${userAuthToken}`,
            },
        });
        const userDetailsResp = yield userDetailsReq.json();
        if (userDetailsResp.user) {
            logger_1.Logger.meetingMetadata.peerId = peerId;
            logger_1.Logger.meetingMetadata.sdkVersion = '0.24.0';
            logger_1.Logger.meetingMetadata.roomName = meeting.setupConfig.roomName;
            logger_1.Logger.meetingMetadata.organizationId =
                meeting.setupConfig.clientId;
            if (react_native_1.Platform.OS === 'android') {
                logger_1.Logger.meetingMetadata.deviceInfo = {
                    brand: react_native_1.Platform.constants.Brand,
                    model: react_native_1.Platform.constants.Model,
                    osVersion: react_native_1.Platform.constants.Version,
                };
            }
            else if (react_native_1.Platform.OS === 'ios') {
                logger_1.Logger.meetingMetadata.deviceInfo = {
                    isIpad: react_native_1.Platform.isPad,
                    osVersion: react_native_1.Platform.constants.osVersion,
                };
            }
            logger_1.default.warn('init');
            /* LogRocket.identify(userDetailsResp.user.id, {
                name: userDetailsResp.user.name,
                email: userDetailsResp.user.email,
            }); */
            if (userDetailsResp.user.email.endsWith('@anon.dyte.in')) {
                delete userDetailsResp.user.email;
                delete userDetailsResp.user.name;
            }
            client.setHeader('Authorization', `Bearer ${userAuthToken}`);
            dispatch(participantSlice_1.setUser(Object.assign(Object.assign({}, userDetailsResp.user), { authToken: userAuthToken })));
        }
    });
    const processPreset = (preset) => __awaiter(void 0, void 0, void 0, function* () {
        let newConfig;
        if ((preset === null || preset === void 0 ? void 0 : preset.uiConfig) || (preset === null || preset === void 0 ? void 0 : preset.role)) {
            newConfig = src_1.convertPresetToV2(meeting.config, preset);
        }
        else {
            newConfig = preset;
        }
        react_redux_1.batch(() => {
            var _a, _b;
            dispatch(roomSlice_1.setPresetFetched(true));
            dispatch(peersSlice_1.peerMetadataUpdated({
                id: peerId,
                view_type: (_a = newConfig.permissions) === null || _a === void 0 ? void 0 : _a.view_type,
                preset_name: newConfig.preset_name,
            }));
            if ((_b = newConfig.permissions) === null || _b === void 0 ? void 0 : _b.view_type) {
                dispatch(roomSlice_1.setRoomViewType(newConfig.permissions.view_type));
            }
            if (sessionConfig.permissions.view_type !==
                src_1.DyteViewTypes.groupCall &&
                newConfig.permissions.view_type === src_1.DyteViewTypes.groupCall) {
                dispatch(participantSlice_1.switchToGroupCall());
            }
            if (sessionConfig.permissions.view_type !== src_1.DyteViewTypes.webinar &&
                newConfig.permissions.view_type === src_1.DyteViewTypes.webinar) {
                dispatch(participantSlice_1.updateWebinarPresentingSetting(true));
                dispatch(participantSlice_1.updateCanPresent(newConfig.permissions.can_present));
                dispatch(peersSlice_1.switchToWebinar());
            }
            else if (newConfig.permissions.hidden_participant) {
                const visibilty = {
                    hidden: true,
                    joinStageSettings: participantSlice_1.JoinStageSettings.ALLOWED,
                };
                dispatch(participantSlice_1.setVisibilitySettings(visibilty));
            }
        });
        updateConfig(Object.assign({}, lodash_merge_1.default(meeting.config, newConfig)));
    });
    const saveUserV2 = (userAuthToken) => __awaiter(void 0, void 0, void 0, function* () {
        var _a;
        const userDetailsReq = yield fetch(`${config_1.default.apiBase}/v2/internals/participant-details`, {
            method: 'GET',
            headers: {
                authorization: `Bearer ${userAuthToken}`,
            },
        });
        const userDetailsResp = yield userDetailsReq.json();
        const participant = (_a = userDetailsResp.data) === null || _a === void 0 ? void 0 : _a.participant;
        logger_1.Logger.meetingMetadata.peerId = peerId;
        logger_1.Logger.meetingMetadata.sdkVersion = '0.24.0';
        logger_1.Logger.meetingMetadata.organizationId = participant.organization_id;
        if (react_native_1.Platform.OS === 'android') {
            logger_1.Logger.meetingMetadata.deviceInfo = {
                brand: react_native_1.Platform.constants.Brand,
                model: react_native_1.Platform.constants.Model,
                osVersion: react_native_1.Platform.constants.Version,
            };
        }
        else if (react_native_1.Platform.OS === 'ios') {
            logger_1.Logger.meetingMetadata.deviceInfo = {
                isIpad: react_native_1.Platform.isPad,
                osVersion: react_native_1.Platform.constants.osVersion,
            };
        }
        logger_1.default.warn('init');
        client.setHeader('Authorization', `Bearer ${userAuthToken}`);
        dispatch(participantSlice_1.setUser({
            clientSpecificId: participant.custom_participant_id,
            organizationId: participant.organization_id,
            name: participant.name,
            picture: participant.picture,
            loggedIn: true,
            authToken: userAuthToken
        }));
        if (userDetailsResp.data.preset) {
            const { preset } = userDetailsResp.data;
            processPreset(utils_1.convertHybridPresetToV1(utils_1.convertV2PresetToHybrid(preset)));
        }
    });
    const updatePreset = (roomName, authToken) => __awaiter(void 0, void 0, void 0, function* () {
        var _b;
        try {
            const userPresetReq = yield fetch(`${config_1.default.apiBase}/v1/userpreset`, {
                method: 'POST',
                headers: {
                    'content-type': 'application/json',
                },
                body: JSON.stringify({
                    authToken,
                    roomName,
                    version: '0.5.0',
                    clientType: 'CLIENT_APP',
                }),
            });
            const userPresetResp = yield userPresetReq.json();
            if ((_b = userPresetResp === null || userPresetResp === void 0 ? void 0 : userPresetResp.data) === null || _b === void 0 ? void 0 : _b.preset) {
                const { preset } = userPresetResp.data;
                processPreset(preset);
            }
        }
        catch (e) {
            // paass
            updateConfig(meeting.config);
        }
    });
    const anonLogin = () => {
        fetch(`${config_1.default.apiBase}/auth/anonymous`)
            .then((resp) => resp.json())
            .then((resp) => {
            const { id } = parseJwt(resp.authToken);
            dispatch(participantSlice_1.setUser({ authToken: resp.authToken, id }));
            client.setHeader('Authorization', `Bearer ${resp.authToken}`);
            setAuthToken(true);
        });
    };
    react_1.useEffect(() => {
        if (meeting) {
            if (meeting.setupConfig.authToken) {
                client.setHeader('Authorization', `Bearer ${meeting.setupConfig.authToken}`);
                if (config_1.isV2AuthToken(meeting.setupConfig.authToken)) {
                    saveUserV2(meeting.setupConfig.authToken);
                }
                else {
                    saveUser(meeting.setupConfig.authToken);
                }
                setAuthToken(true);
            }
            else {
                anonLogin();
            }
            meeting._controlsHook = (control) => {
                setParticipantControls((p) => p.concat(control));
            };
            meeting._setUIConfig = updateConfig;
        }
    }, [meeting]);
    react_1.useEffect(() => {
        var _a, _b;
        const meetingDimensions = ((_b = (_a = meeting.config) === null || _a === void 0 ? void 0 : _a.theme) === null || _b === void 0 ? void 0 : _b.dimensions) || {};
        const { width, height } = meetingDimensions;
        if ((isLandscape && width < height) ||
            (!isLandscape && height < width)) {
            meetingDimensions.width = height;
            meetingDimensions.height = width;
            updateConfig(Object.assign({}, meeting.config));
        }
    }, [orientation]);
    react_1.useEffect(() => {
        if (meeting) {
            dispatch(roomSlice_1.resetRoom({}));
            dispatch(participantSlice_1.resetParticipant());
            dispatch(peersSlice_1.resetPeers());
        }
        else
            anonLogin();
        return () => {
            dispatch(store_1.resetEverything());
        };
    }, [meeting.setupConfig.roomName, meeting.setupConfig.authToken]);
    // 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,
    };
    react_1.useEffect(() => {
        // LogRocket.init('bhibaz/dyte-mobile');
    }, []);
    if (!authToken)
        return react_1.default.createElement(react_1.default.Fragment, null);
    return (react_1.default.createElement(exports.ConfigServiceContext.Provider, { value: context },
        react_1.default.createElement(CustomThemeChakraProvider_1.default, null, children)));
};
exports.ConfigServiceProvider = ConfigServiceProvider;
//# sourceMappingURL=ConfigProvider.js.map