import React, { createContext, useCallback, useContext, useMemo } from 'react';
import { useUser } from '../auth/useUser';
import { useAxiosGet } from '../useAxiosGet';
import { ConfigService } from '../../configService';
import { getRouteRolesMapAndMenuActiveMap, findHomeRouteSlug } from './menuUtilities';
export const MenuContext = createContext(null);
const buildRouteAndActiveMaps = (menu) => {
    const rawResult = getRouteRolesMapAndMenuActiveMap(menu);
    const rolesMap = new Map();
    if ((rawResult === null || rawResult === void 0 ? void 0 : rawResult.rolesMap) instanceof Map) {
        rawResult.rolesMap.forEach((value, key) => {
            if (typeof key !== 'string')
                return;
            const normalizedKey = key;
            const normalizedValue = Array.isArray(value)
                ? value.map((roleId) => String(roleId))
                : [];
            rolesMap.set(normalizedKey, normalizedValue);
        });
    }
    const menuActiveMap = new Map();
    if ((rawResult === null || rawResult === void 0 ? void 0 : rawResult.menuActiveMap) instanceof Map) {
        rawResult.menuActiveMap.forEach((value, key) => {
            if (typeof key !== 'string')
                return;
            menuActiveMap.set(key, Boolean(value));
        });
    }
    return { rolesMap, menuActiveMap };
};
export const MenuProvider = ({ children }) => {
    const user = useUser();
    const currentTenantId = user === null || user === void 0 ? void 0 : user.currentTenantId;
    const userId = user === null || user === void 0 ? void 0 : user.id;
    const [{ data: leftMenu, loading: leftMenuLoading, error: leftMenuError }, refetchLeftMenu] = useAxiosGet(ConfigService.tenantV1ApiUrl, `menus?menuTypeId=1&productId=${ConfigService.config.UNITY_PRODUCT_ID}&tenantId=${currentTenantId}`, {}, !currentTenantId);
    const [{ data: appSelectorMenus, loading: appSelectorMenusLoading, error: appSelectorMenusError }, refetchAppSelectorMenus] = useAxiosGet(ConfigService.tenantV1ApiUrl, `menus?tenantId=${currentTenantId}&verticalId=${ConfigService.config.UNITY_VERTICAL_ID}&userId=${userId !== null && userId !== void 0 ? userId : ''}`, {}, !userId);
    const [{ data: languages, loading: languagesLoading, error: languagesError }, refetchLanguages] = useAxiosGet(ConfigService.tenantV1ApiUrl, `language`, {}, !userId);
    const { rolesMap, menuActiveMap, homeRoute } = useMemo(() => {
        if (Array.isArray(leftMenu) && leftMenu.length > 0) {
            return Object.assign(Object.assign({}, buildRouteAndActiveMaps(leftMenu)), { homeRoute: findHomeRouteSlug(leftMenu) });
        }
        return {
            rolesMap: new Map(),
            menuActiveMap: new Map(),
            homeRoute: null
        };
    }, [leftMenu]);
    const refetchAll = useCallback(() => {
        const refetchPromises = [];
        if (currentTenantId) {
            refetchPromises.push(refetchLeftMenu());
        }
        if (userId) {
            refetchPromises.push(refetchAppSelectorMenus());
        }
        refetchPromises.push(refetchLanguages());
        return Promise.all(refetchPromises);
    }, [
        currentTenantId,
        refetchAppSelectorMenus,
        refetchLanguages,
        refetchLeftMenu,
        userId
    ]);
    const value = useMemo(() => ({
        leftMenu,
        leftMenuLoading,
        leftMenuError,
        appSelectorMenus,
        appSelectorMenusLoading,
        appSelectorMenusError,
        languages,
        languagesLoading,
        languagesError,
        rolesMap,
        menuActiveMap,
        homeRoute,
        refetchAll
    }), [
        leftMenu,
        leftMenuLoading,
        leftMenuError,
        appSelectorMenus,
        appSelectorMenusLoading,
        appSelectorMenusError,
        languages,
        languagesLoading,
        languagesError,
        rolesMap,
        menuActiveMap,
        homeRoute,
        refetchAll
    ]);
    return React.createElement(MenuContext.Provider, { value: value }, children);
};
export const useMenuContext = () => {
    const context = useContext(MenuContext);
    return (context !== null && context !== void 0 ? context : {
        leftMenuLoading: false,
        appSelectorMenusLoading: false,
        languagesLoading: false,
        rolesMap: new Map(),
        menuActiveMap: new Map(),
        homeRoute: null,
        refetchAll: () => Promise.resolve([])
    });
};
//# sourceMappingURL=MenuProvider.js.map