"use strict";

exports.__esModule = true;
exports.useNavigationState = exports.getPageData = exports.default = void 0;
var _reactRedux = require("react-redux");
var _reactRouterDom = require("react-router-dom");
var _utils = require("../../utils");
var _navigation = require("../../actions/navigation");
var _navigation2 = require("../../selectors/navigation");
var _scope = require("../../selectors/scope");
var _parseHelper = require("../../utils/parseHelper");
(function () {
  var enterModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.enterModule : undefined;
  enterModule && enterModule(module);
})();
(function () {
  var enterModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.enterModule : undefined;
  enterModule && enterModule(module);
})();
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
var __signature__ = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default.signature : function (a) {
  return a;
};
var __signature__ = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default.signature : function (a) {
  return a;
};
var doesRestPathMatchParams = function doesRestPathMatchParams(params, paramPathSplit, restPath) {
  var restPathMatchParams = true;
  for (var i = 1; i < paramPathSplit.length; i++) {
    if (restPath[i - 1] !== "/" + params[paramPathSplit[i]]) {
      restPathMatchParams = false;
      break;
    }
  }
  return restPathMatchParams;
};
var _getPageWithSplitPath = function getPageWithSplitPath(_ref, params, pages) {
  var _ref2 = _toArray(_ref),
    pathStep = _ref2[0],
    restPath = _ref2.slice(1);
  var page = getPageFromPathSteps(pages, pathStep);
  if (!page) {
    var paramPath =
    // Only one should exist
    Object.keys(pages).filter(function (path) {
      return /^\/:/.test(path);
    })[0] || "";

    // removes the first '/:' from the URL
    // remove the regex of the parameters, the part between parentheses (path to regex syntax)
    // split on the remaining '/:'
    var paramPathSplit = paramPath.replace(/^\/:/, "").replace(/(\([^/]+?\))/g, "").split("/:");
    var firstStepMatchParams = pathStep === "/" + params[paramPathSplit[0]];
    if (firstStepMatchParams) {
      if (paramPathSplit.length === 1) {
        page = pages[paramPath];
      } else if (paramPathSplit.length - 1 === restPath.length && doesRestPathMatchParams(params, paramPathSplit, restPath)) {
        return pages[paramPath];
      }
    }
  }
  if (restPath.length === 0 || !page) {
    return page;
  } else {
    return _getPageWithSplitPath(restPath, params, _objectSpread(_objectSpread(_objectSpread({}, page.pages), page.segments), page.subpages));
  }
};
var getPageFromPathSteps = function getPageFromPathSteps(pages, pathStep) {
  var page = pages[pathStep];
  if (page) {
    return page;
  }
  var rx = /^\/:[^(]+\(([^/]+?)\)/;
  for (var _i = 0, _Object$keys = Object.keys(pages); _i < _Object$keys.length; _i++) {
    var key = _Object$keys[_i];
    var matches = key.match(rx);
    if (matches !== null) {
      if (new RegExp(matches[1]).test(pathStep)) {
        return pages[key];
      }
    }
  }
  return undefined;
};
var redirectScopeWhenRequired = function redirectScopeWhenRequired(isPageTab, pageScopeSelector, rawPage, currentScope, scopeDefinitionGetter) {
  var params = rawPage.params || {};
  var scopeChanged = params.scope && params.scope !== currentScope;
  var currentScopeDefinition = scopeDefinitionGetter(currentScope);
  var currentScopePath = currentScopeDefinition ? currentScopeDefinition.scopePath : [];
  var outsideScope = scopeChanged;
  if (isPageTab && pageScopeSelector) {
    if (scopeChanged) {
      rawPage = _objectSpread(_objectSpread({}, rawPage), {}, {
        params: _objectSpread({}, params)
      });
      rawPage.href = rawPage.href.replace("/".concat(rawPage.params.scope, "/"), "/".concat(currentScope, "/"));
      rawPage.params.scope = currentScope;
    }
    var scopeId = pageScopeSelector(params);
    var scopeFromPageState = scopeId ? scopeDefinitionGetter(scopeId) : null;
    if (scopeFromPageState) {
      outsideScope = scopeFromPageState.id !== currentScope && currentScopePath.indexOf(scopeFromPageState.id) < 0 && scopeFromPageState.scopePath.indexOf(currentScope) < 0;
    }
  }
  return [rawPage, outsideScope];
};
var getPageData = exports.getPageData = function getPageData(path, params, module) {
  if (!path) return module;
  var pathSteps = path.split(/(?=\/)/);
  return _getPageWithSplitPath(pathSteps, params, _objectSpread(_objectSpread(_objectSpread({}, module.pages), module.segments), module.subpages));
};
var useNavigationState = exports.useNavigationState = function useNavigationState(modules) {
  var _moduleData$closingTa4;
  var dispatch = (0, _reactRedux.useDispatch)();
  var _useLocation = (0, _reactRouterDom.useLocation)(),
    currentHref = _useLocation.pathname;
  var store = (0, _reactRedux.useStore)();
  var hrefMapper = (0, _reactRedux.useSelector)(_navigation2.selectSegmentHrefMapper);
  var prependPath = (0, _reactRedux.useSelector)(_navigation2.selectPrependPathConfig);
  var _getModuleNameFromHre = (0, _parseHelper.getModuleNameFromHref)(prependPath, currentHref),
    _getModuleNameFromHre2 = _slicedToArray(_getModuleNameFromHre, 2),
    moduleName = _getModuleNameFromHre2[0],
    moduleHref = _getModuleNameFromHre2[1];
  var moduleData = modules[moduleName] /* istanbul ignore next */ || {};
  var rawModule = {
    icon: moduleData.icon,
    label: moduleData.label,
    href: moduleHref
  };
  var currentScope = (0, _reactRedux.useSelector)(_navigation2.getCurrentScope);
  var scopeDefinitionGetter = (0, _reactRedux.useSelector)(_scope.scopeGetter);
  var rawPages = (0, _utils.unwrapImmutable)((0, _reactRedux.useSelector)(_navigation2.selectMappedCurrentModuleList)).filter(function (page) {
    if (!page) return false;
    var _getModuleNameFromHre3 = (0, _parseHelper.getModuleNameFromHref)(prependPath, page.href),
      _getModuleNameFromHre4 = _slicedToArray(_getModuleNameFromHre3, 2),
      pageModuleName = _getModuleNameFromHre4[0],
      pageModuleHref = _getModuleNameFromHre4[1];
    return page.href !== pageModuleHref || pageModuleName !== moduleName;
  });
  var _map = [rawModule].concat(rawPages).map(function (rawPage) {
      var isPageTab = !rawPage.icon;
      var pageScopeSelector = moduleData.pageScopeSelector ? function (params) {
        return moduleData.pageScopeSelector(store.getState(), params);
      } : null;
      var _redirectScopeWhenReq = redirectScopeWhenRequired(isPageTab, pageScopeSelector, rawPage, currentScope, scopeDefinitionGetter),
        _redirectScopeWhenReq2 = _slicedToArray(_redirectScopeWhenReq, 2),
        page = _redirectScopeWhenReq2[0],
        outsideScope = _redirectScopeWhenReq2[1];
      var params = page.params || {};
      var _getModuleNameFromHre5 = (0, _parseHelper.getModuleNameFromHref)(prependPath, page.href),
        _getModuleNameFromHre6 = _slicedToArray(_getModuleNameFromHre5, 2),
        pageBaseHref = _getModuleNameFromHre6[1];
      var pageData = getPageData(page.href.replace(pageBaseHref, ""), params, moduleData) || {
        label: "[Not found]"
      };
      var icon = pageData.icon;
      var isDetails = pageData.isDetails;
      var label = pageData.label;
      if (label && label.id) {
        label = _objectSpread({}, label);
        if (pageData.labelValueSelector) {
          label.values = pageData.labelValueSelector(params);
          if (typeof label.values !== "function") {
            delete label.values;
          }
        } else if (Array.isArray(pageData.dataPath)) {
          console.warn("Using dataPath label value pointers is deprecated, use labelValueSelector instead");
          var dataPath = [].concat(pageData.dataPath);
          /* istanbul ignore else */
          if (pageData.dataIdParam) {
            dataPath.push(params[pageData.dataIdParam]);
          }
          label.values = function (state) {
            return state.getIn(dataPath);
          };
        }
      }
      var href = hrefMapper(page.href);

      // Modules do not have close functions
      var close = isPageTab ? function (event, executeHandlerOnly) {
        var _moduleData$closingTa, _moduleData$closingTa2;
        if (executeHandlerOnly === void 0) {
          executeHandlerOnly = false;
        }
        var result = Promise.resolve();
        if ((_moduleData$closingTa = moduleData.closingTabHandler) != null && _moduleData$closingTa.handler && (_moduleData$closingTa2 = moduleData.closingTabHandler) != null && _moduleData$closingTa2.entitySelector) {
          var _moduleData$closingTa3;
          var entityContext = (_moduleData$closingTa3 = moduleData.closingTabHandler.entitySelector(params, store.getState())) != null ? _moduleData$closingTa3 : null;
          if ((entityContext == null ? void 0 : entityContext.entityId) != null && (entityContext == null ? void 0 : entityContext.entity) != null) {
            result = moduleData.closingTabHandler.handler(dispatch, params, entityContext.entityId, entityContext.entity);
          }
        }
        if (executeHandlerOnly === false) {
          dispatch((0, _navigation.removeTab)(moduleName, page.href));
        }
        if (event) {
          event.stopPropagation();
          event.preventDefault();
        }
        return result;
      } : undefined;
      return _objectSpread(_objectSpread({}, page), {}, {
        outsideScope: isPageTab ? outsideScope : null,
        scopeNotSupported: isPageTab ? pageScopeSelector != null && outsideScope : null,
        label: label,
        entityIdResolver: pageData.entityIdResolver,
        mustTruncate: pageData.mustTruncate,
        href: href,
        mappedFrom: page.href,
        active: href === currentHref,
        close: close,
        icon: icon,
        isDetails: isDetails
      });
    }),
    _map2 = _toArray(_map),
    module = _map2[0],
    pages = _map2.slice(1);
  module.closingTabHandler = (_moduleData$closingTa4 = moduleData.closingTabHandler) != null ? _moduleData$closingTa4 : null;
  return {
    module: module,
    pages: pages,
    moduleName: moduleName,
    moduleHref: hrefMapper(moduleHref)
  };
};
__signature__(useNavigationState, "useDispatch{dispatch}\nuseLocation{{ pathname: currentHref }}\nuseStore{store}\nuseSelector{hrefMapper}\nuseSelector{prependPath}\nuseSelector{currentScope}\nuseSelector{scopeDefinitionGetter}\nuseSelector{}", function () {
  return [_reactRedux.useDispatch, _reactRouterDom.useLocation, _reactRedux.useStore, _reactRedux.useSelector, _reactRedux.useSelector, _reactRedux.useSelector, _reactRedux.useSelector, _reactRedux.useSelector];
});
__signature__(useNavigationState, "useDispatch{dispatch}\nuseLocation{{ pathname: currentHref }}\nuseStore{store}\nuseSelector{hrefMapper}\nuseSelector{prependPath}\nuseSelector{currentScope}\nuseSelector{scopeDefinitionGetter}\nuseSelector{}", function () {
  return [_reactRedux.useDispatch, _reactRouterDom.useLocation, _reactRedux.useStore, _reactRedux.useSelector, _reactRedux.useSelector, _reactRedux.useSelector, _reactRedux.useSelector, _reactRedux.useSelector];
});
var _default = useNavigationState;
var _default2 = _default;
var _default3 = exports.default = _default2;
;
(function () {
  var reactHotLoader = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default : undefined;
  if (!reactHotLoader) {
    return;
  }
  reactHotLoader.register(doesRestPathMatchParams, "doesRestPathMatchParams", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(_getPageWithSplitPath, "getPageWithSplitPath", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(getPageFromPathSteps, "getPageFromPathSteps", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(redirectScopeWhenRequired, "redirectScopeWhenRequired", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(getPageData, "getPageData", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(useNavigationState, "useNavigationState", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(_default, "default", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
})();
;
(function () {
  var leaveModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.leaveModule : undefined;
  leaveModule && leaveModule(module);
})();
;
(function () {
  var reactHotLoader = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default : undefined;
  if (!reactHotLoader) {
    return;
  }
  reactHotLoader.register(doesRestPathMatchParams, "doesRestPathMatchParams", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(_getPageWithSplitPath, "getPageWithSplitPath", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(getPageFromPathSteps, "getPageFromPathSteps", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(redirectScopeWhenRequired, "redirectScopeWhenRequired", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(getPageData, "getPageData", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(useNavigationState, "useNavigationState", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
  reactHotLoader.register(_default2, "default", "/home/vsts/work/1/s/src/components/Navigation/useNavigationState.js");
})();
;
(function () {
  var leaveModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.leaveModule : undefined;
  leaveModule && leaveModule(module);
})();