var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import * as Icons from '@fluentui/react-icons';
import { UdpPageEnums } from '../../enums/pageEnums';
import { isMobileOnly, isTablet, isDesktop } from 'react-device-detect';
import { DeviceTypeEnums, MenuItemEnums } from '../../enums/unitySystemEnums';
import { getAccessToken } from '../apiHelpers';
// Internal-route menu types that render as real <a href> links. For these we
// build a tenant-carrying href variant; the menu swaps it in only on new-tab
// interactions (right/middle/modified click) so normal SPA navigation keeps a
// clean URL while opening in a new tab preserves the active tenant.
const TENANT_AWARE_MENU_TYPES = [
    MenuItemEnums.Page,
    MenuItemEnums.Route,
    MenuItemEnums.Inquiry,
    MenuItemEnums.Report
];
const getTenantAwareHref = (link, user, menuItemId) => {
    if (!link || !(user === null || user === void 0 ? void 0 : user.currentTenantId))
        return undefined;
    if (user.currentTenantId === user.defaultTenantId)
        return undefined;
    if (!TENANT_AWARE_MENU_TYPES.includes(menuItemId))
        return undefined;
    const separator = link.includes('?') ? '&' : '?';
    return `${link}${separator}tenantId=${user.currentTenantId}`;
};
export const getMenuItemsRecursively = (menuItems, activeOnly, user, checkDeviceSize = true) => {
    return menuItems.reduce((formattedItems, item) => {
        var _a, _b, _c, _d;
        var _e;
        try {
            if (activeOnly && !item.menuItemInstance.isActive) {
                return formattedItems;
            }
            const parameters = JSON.parse(item.menuItemInstance.parameters);
            const { FluentIcon, WorkFlowIcon, AppIcon, Label, Slug, RedirectURL, AppendTokenToURL, DevicesHiddenOn, appendCurrentTenant } = parameters, otherParams = __rest(parameters, ["FluentIcon", "WorkFlowIcon", "AppIcon", "Label", "Slug", "RedirectURL", "AppendTokenToURL", "DevicesHiddenOn", "appendCurrentTenant"]);
            let redirectInfo = '';
            if (RedirectURL) {
                redirectInfo = RedirectURL;
                if (appendCurrentTenant) {
                    redirectInfo = `${RedirectURL}?tenantId=${(user === null || user === void 0 ? void 0 : user.currentTenantId) || ''}`;
                }
            }
            const link = (_e = getFormattedSlug(Slug, Object.assign({}, otherParams))) !== null && _e !== void 0 ? _e : '';
            const formattedParameters = {
                id: item.menuItemInstance.menuItemInstanceId,
                label: Label !== null && Label !== void 0 ? Label : '',
                link,
                tenantHref: getTenantAwareHref(link, user, item.menuItemInstance.menuItemId),
                redirectInfo: redirectInfo,
                getAccessToken: getAccessToken && AppendTokenToURL ? getAccessToken : null,
                menuItemId: item.menuItemInstance.menuItemId,
                menuStructureId: item.menuStructureId,
                parentId: item.parentId,
                productId: item.menuItemInstance.productId,
                isActive: item.menuItemInstance.isActive,
                roleIds: item.menuItemInstance.roleIds,
                tenantSsoId: (_a = item === null || item === void 0 ? void 0 : item.menuItemInstance) === null || _a === void 0 ? void 0 : _a.tenantSsoId,
                devicesHiddenOn: DevicesHiddenOn || [],
                params: Object.assign({}, otherParams)
            };
            let iconName = '';
            if (FluentIcon) {
                iconName = FluentIcon;
            }
            else if (WorkFlowIcon) {
                iconName = WorkFlowIcon;
            }
            formattedParameters.icon = iconName ? Icons[iconName] : null;
            formattedParameters.iconName = iconName ? iconName : null;
            formattedParameters['items'] = item.menuItemInstanceStructures.length
                ? getMenuItemsRecursively(item.menuItemInstanceStructures, activeOnly, user, getAccessToken, checkDeviceSize)
                : [];
            if (checkDeviceSize) {
                if (!(isDesktop &&
                    ((_b = formattedParameters === null || formattedParameters === void 0 ? void 0 : formattedParameters.devicesHiddenOn) === null || _b === void 0 ? void 0 : _b.includes(DeviceTypeEnums.Desktop))) &&
                    !(isTablet &&
                        ((_c = formattedParameters === null || formattedParameters === void 0 ? void 0 : formattedParameters.devicesHiddenOn) === null || _c === void 0 ? void 0 : _c.includes(DeviceTypeEnums.Tablet))) &&
                    !(isMobileOnly &&
                        ((_d = formattedParameters === null || formattedParameters === void 0 ? void 0 : formattedParameters.devicesHiddenOn) === null || _d === void 0 ? void 0 : _d.includes(DeviceTypeEnums.Mobile)))) {
                    formattedItems.push(formattedParameters);
                }
            }
            else {
                formattedItems.push(formattedParameters);
            }
        }
        catch (_f) {
            // catching parse error
        }
        return formattedItems;
    }, []);
};
const getFormattedSlug = (slug, params) => {
    let formattedSlug = slug;
    if ((params === null || params === void 0 ? void 0 : params.PageId) === UdpPageEnums.Udp_Maintenance_Engine_Page) {
        formattedSlug = `${slug}${(params === null || params === void 0 ? void 0 : params.entityName) ? `?entityName=${params === null || params === void 0 ? void 0 : params.entityName}` : ''}`;
    }
    else if ((params === null || params === void 0 ? void 0 : params.PageId) === UdpPageEnums.Udp_Data_Browser_Page) {
        formattedSlug = `${slug}?queryId=${params === null || params === void 0 ? void 0 : params.queryId}`;
    }
    return formattedSlug;
};
const findHomeRouteInStructures = (structures) => {
    var _a;
    var _b;
    for (const item of structures) {
        try {
            const params = JSON.parse(item.menuItemInstance.parameters);
            if (params === null || params === void 0 ? void 0 : params.isHomeRoute) {
                return (_b = params.Slug) !== null && _b !== void 0 ? _b : null;
            }
        }
        catch (_c) {
            // ignore parse errors
        }
        if ((_a = item.menuItemInstanceStructures) === null || _a === void 0 ? void 0 : _a.length) {
            const found = findHomeRouteInStructures(item.menuItemInstanceStructures);
            if (found)
                return found;
        }
    }
    return null;
};
export const findHomeRouteSlug = (menu) => {
    var _a;
    for (const m of menu) {
        if (!m.active)
            continue;
        const found = findHomeRouteInStructures((_a = m.menuItemInstanceStructureViews) !== null && _a !== void 0 ? _a : []);
        if (found)
            return found;
    }
    return null;
};
export const getRouteRolesMapAndMenuActiveMap = (menu) => {
    const updatedRolesMap = new Map();
    const updatedisMenuActiveMap = new Map();
    const activeMenus = menu.filter((m) => m.isActive);
    activeMenus.forEach((m) => {
        m.menuItemInstanceStructureViews.map((menuItemInstanceStructureView) => {
            let menuItemInstance = menuItemInstanceStructureView.menuItemInstance;
            if (menuItemInstance.menuItemId == MenuItemEnums.Route ||
                menuItemInstance.menuItemId == MenuItemEnums.Page ||
                menuItemInstance.menuItemId == MenuItemEnums.Report ||
                menuItemInstance.menuItemId == MenuItemEnums.Inquiry ||
                menuItemInstance.menuItemId == MenuItemEnums.Inner_Menu) {
                try {
                    const menuparams = JSON.parse(menuItemInstance.parameters);
                    const slug = menuparams === null || menuparams === void 0 ? void 0 : menuparams.Slug;
                    updatedRolesMap.set(slug, menuItemInstance.roleIds);
                    updatedisMenuActiveMap.set(slug, menuItemInstance.isActive);
                }
                catch (e) {
                    console.error('Failed to parse menu item parameters', e);
                }
            }
        });
    });
    return { rolesMap: updatedRolesMap, menuActiveMap: updatedisMenuActiveMap };
};
//# sourceMappingURL=menuUtilities.js.map