import RenderAuthorize from '@/components/Authorized';
import { isDev } from './tools.ts';
// const isDev = false;
let auth = [];
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable import/no-mutable-exports */
let Authorized = RenderAuthorize(getAuthority());

// Reload the rights component
const reloadAuthorized = () => {
  Authorized = RenderAuthorize(getAuthority());
};

/**
 * hard code
 * block need it。
 */
window.reloadAuthorized = reloadAuthorized;

export { reloadAuthorized };
export default Authorized;

// use localStorage to store the authority info, which might be sent from server in actual project.
export function getAuthority(str) {
  if (!isDev) return [...auth];
  const authorityString =
    typeof str === 'undefined' && localStorage
      ? localStorage.getItem('panda-oms-authority')
      : str;
  // authorityString could be admin, "admin", ["admin"]
  let authority;
  try {
    if (authorityString) {
      authority = JSON.parse(authorityString);
    }
  } catch (e) {
    authority = authorityString;
  }
  if (typeof authority === 'string') {
    return [authority];
  }

  return authority;
}

export function setAuthority(authority) {
  const proAuthority = typeof authority === 'string' ? [authority] : authority;
  if (isDev) {
    localStorage.setItem('panda-oms-authority', JSON.stringify(proAuthority));
  } else {
    auth = proAuthority;
  }
  // auto reload
  reloadAuthorized();
}
