"use strict";

exports.__esModule = true;
exports.default = exports.useNavigationState = exports.getPageData = 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(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

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 = 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 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 = 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));
};

exports.getPageData = getPageData;

var 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 */

        /* 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

    // 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)
  };
};

exports.useNavigationState = useNavigationState;

__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 = _default2;
exports.default = _default3;
;

(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(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(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);
})();