import { useContext, useMemo } from "react";
import { UserPermissionsContext } from "./UserPermissionsProvider";

const permissionCodes = {
  VIEW_DASHBOARD: "VIEW_DASHBOARD",
  MANAGE_USERS: "MANAGE_USERS",
  MANAGE_SETTINGS: "MANAGE_SETTINGS",
  VIEW_MACHINES: "VIEW_MACHINES",
  MANAGE_MACHINES: "MANAGE_MACHINES",
  OPERATE_MACHINES: "OPERATE_MACHINES",
  GUEST_ACCESS: "GUEST_ACCESS",
  SYSTEM_ADMINISTRATION: "SYSTEM_ADMINISTRATION"
};

const getPermissionFlags = (permissions: string[]) => {
  const viewDashboard = permissions.includes(permissionCodes.VIEW_DASHBOARD) ?? false;
  const manageUsers = permissions.includes(permissionCodes.MANAGE_USERS) ?? false;
  const manageSettings = permissions.includes(permissionCodes.MANAGE_SETTINGS) ?? false;
  const viewMachines = permissions.includes(permissionCodes.VIEW_MACHINES) ?? false;
  const manageMachines = permissions.includes(permissionCodes.MANAGE_MACHINES) ?? false;
  const operateMachines = permissions.includes(permissionCodes.OPERATE_MACHINES) ?? false;
  const guestAccess = permissions.includes(permissionCodes.GUEST_ACCESS) ?? false;
  const sysAdmin = permissions.includes(permissionCodes.SYSTEM_ADMINISTRATION) ?? false;

  const flags = {
    viewDashboard,
    manageUsers,
    manageSettings,
    viewMachines,
    manageMachines,
    operateMachines,
    guestAccess,
    sysAdmin
  };

  const isGuest = guestAccess === true;
  const isUser = Object.values(flags).includes(true) && !flags.guestAccess;

  return {
    ...flags,
    isGuest,
    isUser
  };
};

const usePermissions = () => {
  const { permissions, loading } = useContext(UserPermissionsContext);
  const flags = useMemo(() => getPermissionFlags(permissions), [permissions]);
  return { loading, ...flags };
};

export { usePermissions };
