"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UserProvider = void 0;
var _react = _interopRequireWildcard(require("react"));
var _LoaderContext = _interopRequireDefault(require("../loader/LoaderContext"));
var _userContext = require("./userContext");
var _tokenService = require("../../services/tokenService");
var _jwtDecode = _interopRequireDefault(require("jwt-decode"));
var _authService = require("../../services/authService");
var _permissionService = require("../../services/permissionService");
var _localstorageService = require("../../services/localstorageService");
var _entityService = require("../../services/entityService");
var _enums = require("../../constants/enums");
var _reactRouterDom = require("react-router-dom");
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const baseUserObject = {
  email: "",
  exp: 0,
  role: [],
  iat: 0,
  iss: "",
  jti: "",
  nbf: 0,
  sub: "",
  userProfile: null,
  linkData: null,
  privileges: null,
  distinctModules: []
};
const reducer = (state, _ref) => {
  let {
    type,
    payload
  } = _ref;
  switch (type === null || type === void 0 ? void 0 : type.toString().toLowerCase()) {
    case "login":
      {
        let userObject = {
          ...state.user,
          ...payload.decode
        };
        let returned = {
          user: {
            ...userObject,
            isAuthenticated: true,
            userProfile: payload.userProfile,
            linkData: null,
            privileges: payload.privileges,
            role: payload.role,
            distinctModules: payload.distinctModules
          },
          token: payload.token
        };
        return returned;
      }
    case "clear":
    case "logout":
      {
        let userObject = {
          ...state.user,
          ...baseUserObject
        };
        return {
          user: {
            ...userObject,
            isAuthenticated: false
          },
          token: ""
        };
      }
    default:
      return state;
  }
};
const UserProvider = _ref2 => {
  let {
    children
  } = _ref2;
  const [waiting, setWaiting] = (0, _react.useState)(-1);
  const {
    updateLoaderStatus
  } = (0, _react.useContext)(_LoaderContext.default);
  const [state, dispatch] = (0, _react.useReducer)(reducer, {
    user: baseUserObject,
    token: null
  });
  const loadScriptsAndStyles = clientName => {
    let id = "scriptContainer";
    const container = document.getElementById(id);
    container.innerHTML = "";
    const script = document.createElement("script");
    script.type = "text/babel";
    script.src = "../../styles/".concat(clientName, "/js/common.js");
    script.onload = function () {};
    script.onerror = function () {};
    container.appendChild(script);
  };
  const getProfileAndPrivileges = function (token, hasMultipleBrands, isPrimaryBrand, isSelf, corpBrandCode) {
    let callbackMethod = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null;
    updateLoaderStatus(true);
    setWaiting(0);
    const decode = (0, _jwtDecode.default)(token);
    (0, _authService.UserProfile)(decode.email).then(userProfile => {
      if (userProfile === undefined || userProfile === null) {
        logout();
      } else {
        (0, _authService.UserPrivileges)(userProfile.id).then(userPrivileges => {
          (0, _permissionService.getAssignablePermissions)(userProfile.brandID).then(data => {
            let assignablePermissions = (0, _permissionService.transformAssignablePermissions)(data);
            const set = () => {
              let role = decode["http://schemas.microsoft.com/ws/2008/06/identity/claims/role"];
              let distinctModules = [];
              for (let c = 0; c < userPrivileges.length; c++) {
                let privilege = userPrivileges[c];
                let moduleName = privilege.moduleName;
                let moduleDescription = privilege.moduleDescription;
                const existing = distinctModules.find(x => x.moduleName === moduleName);
                if (existing === null || existing === undefined) {
                  distinctModules.push({
                    moduleName: moduleName,
                    moduleDescription: moduleDescription
                  });
                }
              }
              userProfile.hasMultipleBrands = hasMultipleBrands;
              userProfile.isPrimaryBrand = isPrimaryBrand;
              userProfile.isSelf = isSelf;
              userProfile.corpBrandCode = corpBrandCode;
              let payload = {
                distinctModules: distinctModules,
                role: role,
                userProfile: userProfile,
                privileges: userPrivileges,
                assignablePermissions: assignablePermissions,
                token: token
              };
              dispatch({
                type: "login",
                payload: payload
              });
              loadScriptsAndStyles(userProfile.brandID);
              if (callbackMethod !== null) {
                callbackMethod();
              }
              updateLoaderStatus(false);
              setWaiting(1);
            };
            set();
          }, error => {
            updateLoaderStatus(false);
            setWaiting(1);
          });
        }, error => {
          updateLoaderStatus(false);
          setWaiting(1);
        });
      }
    }, error => {
      updateLoaderStatus(false);
      setWaiting(1);
    });
  };
  const replaceUrl = function (dashboard) {
    let softReplace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    let entityName = null;
    switch (dashboard) {
      case _enums.dashboardNames.GROUPS:
        {
          entityName = _enums.entityNames.GROUPMANAGEMENT;
          break;
        }
      case _enums.dashboardNames.ROLES:
        {
          entityName = _enums.entityNames.ROLEMANAGEMENT;
          break;
        }
      case _enums.dashboardNames.USERS:
        {
          entityName = _enums.entityNames.USERMANAGEMENT;
          break;
        }
      case _enums.dashboardNames.HOURSOPERATION:
        {
          entityName = _enums.entityNames.HOURSOPERATION;
          break;
        }
      default:
        {
          entityName = "";
          break;
        }
    }
    let url = (0, _entityService.getEntityUrl)(entityName);
    if (softReplace === false) {
      window.location.replace(url);
    } else {
      window.history.replaceState(null, "", url);
    }
  };
  const removeAll = () => {
    /*dispatch({ type: "clear", payload: {} });*/
    (0, _localstorageService.removeAccessToken)();
    /*
    removeHasMultipleBrands();
    removeIsPrimaryBrand();
    removeIsSelf();*/
  };

  const navigate = (0, _reactRouterDom.useNavigate)();
  const logout = function () {
    let redirect = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
    removeAll();
    //dispatch({ type: "logout", payload: {} });
    updateLoaderStatus(false);
    if (redirect === true) {
      navigate("/logout");
    }
  };
  const getTokenDetails = () => {
    let token = (0, _tokenService.getStorageToken)();
    let isInValid = false;
    let isExpired = false;
    let isExpiring = false;
    if ((0, _tokenService.isGivenTokenInvalid)(token) === true || (0, _tokenService.isGivenTokenEmpty)(token) === true) {
      isInValid = true;
    } else {
      isExpired = (0, _tokenService.isGivenTokenExpired)(token);
      isExpiring = (0, _tokenService.isGivenTokenExpiring)(token);
    }
    return {
      token,
      isInValid,
      isExpired,
      isExpiring
    };
  };
  const getBrandSpecificOptions = () => {
    let hasMultipleBrands = (0, _localstorageService.getHasMultipleBrands)();
    let isPrimaryBrand = (0, _localstorageService.getIsPrimaryBrand)();
    let isSelf = (0, _localstorageService.getIsSelf)();
    let corpBrandCode = (0, _localstorageService.getCorpBrandCode)();
    return {
      hasMultipleBrands,
      isPrimaryBrand,
      isSelf,
      corpBrandCode
    };
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_userContext.UserContext.Provider, {
    value: {
      state,
      getProfileAndPrivileges,
      removeAll,
      logout,
      waiting,
      getTokenDetails,
      getBrandSpecificOptions,
      replaceUrl
    },
    children: children
  });
};
exports.UserProvider = UserProvider;