import * as React from "react";
import SideMenu from "./components/SideMenu";

interface Props {
  items: any;
  onMenuItemClick?: any;
}

const protect = (
  roles: string[],
  userRoles: string[],
  permissions: string[],
  userPermissions: string[]
) => {
  return roles.some((role: string) => userRoles.includes(role)) &&
    permissions.some((permission: string) =>
      userPermissions.includes(permission)
    )
    ? true
    : false;
};

const mountMenuItems = (items: any) => {
  let definedStructure: any = [];
  items.forEach((item: any) => {
    protect(
      item.roles,
      item.userRoles,
      item.permissions,
      item.userPermissions
    ) &&
      definedStructure.push({
        ...(item.subLabel && { divider: true }),
        label: item.label,
        value: item.route ? item.route : item.label,
        ...(item.icon && { icon: item.icon }),
      });
    item.items &&
      item.items.forEach((element: any) => {
        if (
          protect(
            element.roles,
            element.userRoles,
            element.permissions,
            element.userPermissions
          )
        ) {
          element.value = element.route;
          definedStructure.push(element);
          element.items &&
            delete Object.assign(element, { ["children"]: element["items"] })[
              "items"
            ];
        }
      });
  });
  return definedStructure;
};

const MagaVerticalMenu = ({ items, onMenuItemClick }: Props) => (
  <SideMenu items={mountMenuItems(items)} onMenuItemClick={onMenuItemClick} />
);

export default MagaVerticalMenu;
