import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectAuthLevel, selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import rbacDefaults from "./rbac-defaults";

const mapStateToProps = createStructuredSelector({
  authLevel: selectAuthLevel,
  bodyshop: selectBodyshop
});

function RbacWrapper({ authLevel, bodyshop, requiredAuthLevel, noauth, children, action }) {
  const { t } = useTranslation();

  if (
    (requiredAuthLevel && requiredAuthLevel <= authLevel) ||
    ((bodyshop.md_rbac && bodyshop.md_rbac[action]) || rbacDefaults[action]) <= authLevel ||
    (bodyshop.md_rbac && !bodyshop.md_rbac[action] && rbacDefaults[action] <= authLevel)
  )
    return children;
  //return <div>{React.cloneElement(children, restProps)}</div>;

  return noauth || <AlertComponent title={t("general.messages.rbacunauth")} type="warning" />;
}

export function HasRbacAccess({ authLevel, bodyshop, requiredAuthLevel, action }) {
  return (
    (requiredAuthLevel && requiredAuthLevel <= authLevel) ||
    ((bodyshop.md_rbac && bodyshop.md_rbac[action]) || rbacDefaults[action]) <= authLevel ||
    (bodyshop.md_rbac && !bodyshop.md_rbac[action] && rbacDefaults[action] <= authLevel)
  );
}

export default connect(mapStateToProps, null)(RbacWrapper);
