"use strict";

exports.__esModule = true;
exports.default = exports.TabLink = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactIntl = require("react-intl");
var _reactRouterDom = require("react-router-dom");
var _reactResizeDetector = _interopRequireDefault(require("react-resize-detector"));
var _reactRedux = require("react-redux");
var _classnames = _interopRequireDefault(require("classnames"));
var _Tabs = _interopRequireDefault(require("@material-ui/core/Tabs"));
var _styles = require("@material-ui/core/styles");
var _Tab = _interopRequireDefault(require("@material-ui/core/Tab"));
var _TabLabel = _interopRequireDefault(require("./TabLabel"));
var _Select = _interopRequireDefault(require("../Inputs/Select"));
var _SelectProps = _interopRequireDefault(require("../Inputs/SelectProps"));
var _Icon = _interopRequireDefault(require("../DataDisplay/Icon"));
var _domHelper = require("./../../../utils/domHelper");
var _view = require("./../../../selectors/view");
var _ConfirmationModal = _interopRequireDefault(require("./../DataDisplay/PredefinedElements/ConfirmationModal"));
var _view2 = require("./../../../actions/view");
var _urlHelper = require("./../../../utils/urlHelper");
var _useDispatchWithModulesData = require("./../../../hooks/useDispatchWithModulesData");
var _sharedMessages = _interopRequireDefault(require("./../../../sharedMessages"));
var _navigation = require("../../../actions/navigation");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
(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 _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 _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 _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
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 useStyles = (0, _styles.makeStyles)(function (theme) {
  return {
    container: {
      flex: "0 0 ".concat(theme.spacing(1)),
      maxHeight: 0,
      padding: "0 0 0 ".concat(theme.spacing(1)),
      margin: "0 ".concat(theme.spacing(20), " 0 0"),
      display: "flex",
      alignItems: "flex-end",
      width: "calc(100% - ".concat(theme.spacing(30), ")")
    },
    tab: {
      flex: "0 0 auto"
    },
    unsetMaxWidth: {
      maxWidth: "unset"
    },
    tabWrapper: {
      "& > *:first-child": {
        order: "1 !important",
        marginLeft: theme.spacing(1),
        color: theme.palette.primary.contrastText,
        "&:hover": {
          color: theme.palette.primary.main
        }
      }
    },
    hidden: {
      visibility: "hidden",
      position: "absolute"
    },
    moduleIcon: {
      width: "".concat(theme.spacing(2.4), " !important"),
      height: theme.spacing(2.4),
      color: "inherit"
    },
    sectionIcon: {
      width: "".concat(theme.spacing(1.6), " !important"),
      height: theme.spacing(1.6)
    },
    select: {
      marginLeft: theme.spacing(2),
      marginBottom: theme.spacing(1),
      zIndex: 100
    },
    closeIcon: {
      marginLeft: theme.spacing(1),
      color: theme.palette.primary.contrastText,
      "&:hover": {
        color: theme.palette.primary.main
      }
    },
    labelContainer: {
      position: "relative",
      width: "100%"
    },
    modifiedLabel: {
      fontWeight: theme.typography.fontWeightBold
    },
    errorLabel: {
      color: theme.palette.error.main,
      fontWeight: theme.typography.fontWeightBold
    },
    asterix: {
      position: "absolute",
      top: theme.spacing(-0.5),
      right: theme.spacing(-0.7)
    }
  };
});
var TabLink = exports.TabLink = _react.default.forwardRef(function (props, ref) {
  return /*#__PURE__*/_react.default.createElement(_reactRouterDom.Link, _extends({
    to: props.to
  }, props, {
    ref: ref
  }), props.children, props.close);
});
var createEntityId = function createEntityId(entityIdResolver, params, href, path) {
  var entityIdKey = Object.keys(params).find(function (p) {
    return p.toLowerCase().endsWith("id");
  });
  if (!entityIdKey) entityIdKey = (0, _urlHelper.tryGetNewEntityIdKey)(href);
  var entityId = typeof entityIdResolver === "function" ? entityIdResolver({
    match: {
      params: params
    }
  }) : (0, _urlHelper.resolveEntityId)(href, path, entityIdKey);
  return {
    entityId: entityId,
    entityIdKey: entityIdKey
  };
};
var MuiBar = function MuiBar(_ref) {
  var module = _ref.module,
    moduleName = _ref.moduleName,
    pages = _ref.pages;
  var tabs = _react.default.useRef(null);
  var classes = useStyles();
  var history = (0, _reactRouterDom.useHistory)();
  var dispatch = (0, _useDispatchWithModulesData.useDispatchWithModulesData)();
  var dispatchRedux = (0, _reactRedux.useDispatch)();
  var activePage = pages.findIndex(function (p) {
    return p.active === true;
  });
  var activeTabIndex = activePage === -1 ? false : activePage;
  var _React$useState = _react.default.useState(false),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    showSelect = _React$useState2[0],
    setShowSelect = _React$useState2[1];
  var _React$useState3 = _react.default.useState(false),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    showConfirmationModal = _React$useState4[0],
    setShowConfirmationModal = _React$useState4[1];
  var _React$useState5 = _react.default.useState(),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    currentCloseData = _React$useState6[0],
    setCurrentCloseData = _React$useState6[1];
  var pagesParams = pages.map(function (page) {
    return {
      href: page.href,
      params: Object.values(page.params)
    };
  });
  var modifiedTabs = (0, _reactRedux.useSelector)((0, _view.getModifiedTabs)(pagesParams));
  var tabsWithErrors = (0, _reactRedux.useSelector)((0, _view.getTabsWithErrors)(pagesParams));
  var tabLabels = [];
  var handleChange = (0, _react.useCallback)(function (_, value) {
    if (typeof value === "number" && value >= 0 && value < pages.length) {
      var href = pages[value].href;
      history.push(href);
    } else {
      history.push(module.href);
    }
  }, [history, module, pages]);
  var selectProps = new _SelectProps.default();
  selectProps.set(_SelectProps.default.propNames.iconSelect, true);
  selectProps.set(_SelectProps.default.propNames.value, activeTabIndex === false ? "" : activeTabIndex);
  selectProps.set(_SelectProps.default.propNames.update, function (newValue) {
    return handleChange(null, newValue);
  });
  var select = /*#__PURE__*/_react.default.createElement("div", {
    className: classes.select
  }, /*#__PURE__*/_react.default.createElement(_Select.default, {
    options: tabLabels,
    selectProps: selectProps
  }));
  var getNewIndex = (0, _react.useCallback)(function (oldIndex) {
    var newIndex = oldIndex + 1 >= tabLabels.length ? oldIndex - 1 : oldIndex + 1;
    return newIndex;
  }, [tabLabels.length]);
  var tabCloseHandler = function tabCloseHandler(event, closeCallback, isModified, href, path, entityIdKey, entityId, index) {
    event.stopPropagation();
    event.preventDefault();
    if (isModified) {
      setCurrentCloseData({
        closeCallback: closeCallback,
        entityId: entityId,
        index: index
      });
      setShowConfirmationModal(true);
    } else {
      closeCallback();
      dispatch(_view2.removeEditNode, [entityId]);
      handleChange(null, getNewIndex(index));
    }
  };
  var closeTab = function closeTab() {
    setShowConfirmationModal(false);
    currentCloseData.closeCallback();
    dispatch(_view2.removeEditNode, [currentCloseData.entityId]);
    handleChange(null, getNewIndex(currentCloseData.index));
  };
  var moduleIcon = /*#__PURE__*/_react.default.createElement(_Icon.default, {
    id: module.icon,
    className: classes.moduleIcon
  });
  var resizeHandler = _react.default.useCallback(function () {
    var scroller = tabs.current.querySelector(".MuiTabs-flexContainer");
    setShowSelect((0, _domHelper.isScrollVisible)(scroller));
  }, [tabs]);
  _react.default.useEffect(function () {
    resizeHandler();
  }, [resizeHandler, module, pages]);
  var allTabs = /*#__PURE__*/_react.default.createElement("div", {
    className: classes.container
  }, /*#__PURE__*/_react.default.createElement(_reactResizeDetector.default, {
    onResize: resizeHandler
  }), /*#__PURE__*/_react.default.createElement(_Tab.default, {
    label: /*#__PURE__*/_react.default.createElement(_TabLabel.default, {
      label: module.label
    }),
    component: _reactRouterDom.Link,
    key: module.href,
    to: module.href,
    icon: moduleIcon,
    onClick: function onClick(e) {
      return handleChange(e, false);
    },
    className: activeTabIndex === false ? "Mui-selected" : null,
    disableFocusRipple: true
  }), /*#__PURE__*/_react.default.createElement(_Tabs.default, {
    value: activeTabIndex,
    onChange: handleChange,
    variant: "scrollable",
    scrollButtons: "off",
    classes: {
      scrollButtons: classes.hidden
    },
    ref: tabs
  }, pages.map(function (_ref2, index) {
    var href = _ref2.href,
      label = _ref2.label,
      outsideScope = _ref2.outsideScope,
      close = _ref2.close,
      path = _ref2.path,
      params = _ref2.params,
      mustTruncate = _ref2.mustTruncate,
      icon = _ref2.icon,
      isDetails = _ref2.isDetails,
      entityIdResolver = _ref2.entityIdResolver;
    var _createEntityId = createEntityId(entityIdResolver, params, href, path),
      entityId = _createEntityId.entityId,
      entityIdKey = _createEntityId.entityIdKey;
    var isModified = modifiedTabs.includes(href);
    var isError = tabsWithErrors.includes(href);
    var tabLabel = /*#__PURE__*/_react.default.createElement(_TabLabel.default, {
      label: label
    });
    var sectionIconClss = (0, _classnames.default)(classes.moduleIcon, isDetails && classes.sectionIcon);
    var tabClassName = (0, _classnames.default)(classes.labelContainer, isModified && classes.modifiedLabel, isError && classes.errorLabel);
    var sectionIcon = icon && /*#__PURE__*/_react.default.createElement(_Icon.default, {
      id: icon,
      className: sectionIconClss
    });
    var wrappedTabLabel = /*#__PURE__*/_react.default.createElement("div", {
      className: tabClassName
    }, /*#__PURE__*/_react.default.createElement(_TabLabel.default, {
      label: label,
      mustTruncate: mustTruncate,
      classes: {
        root: tabClassName
      }
    }), isModified === true ? /*#__PURE__*/_react.default.createElement("span", {
      className: classes.asterix
    }, "*") : null);
    var closeIcon = /*#__PURE__*/_react.default.createElement(_Icon.default, {
      id: "close",
      className: classes.closeIcon,
      onClick: function onClick(event) {
        return tabCloseHandler(event, close, isModified, href, path, entityIdKey, entityId, index);
      }
    });
    tabLabels.push({
      value: index,
      label: tabLabel,
      sortOrder: index
    });
    return /*#__PURE__*/_react.default.createElement(_Tab.default, {
      classes: {
        root: (0, _classnames.default)(classes.tab, !mustTruncate && classes.unsetMaxWidth)
      },
      component: TabLink,
      label: wrappedTabLabel,
      icon: sectionIcon,
      key: href,
      to: href,
      value: index,
      close: closeIcon,
      disabled: outsideScope
    });
  })), showSelect ? select : null, /*#__PURE__*/_react.default.createElement(_ConfirmationModal.default, {
    message: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _sharedMessages.default.unsavedChanges),
    open: showConfirmationModal,
    okCallback: function okCallback() {
      return closeTab();
    },
    cancelCallback: function cancelCallback() {
      return setShowConfirmationModal(false);
    },
    backdropClickCallback: function backdropClickCallback() {
      return setShowConfirmationModal(false);
    }
  }));
  _react.default.useEffect(function () {
    var closingActions = [];
    pages.forEach(function (page, index) {
      var href = page.href,
        close = page.close,
        path = page.path,
        params = page.params,
        entityIdResolver = page.entityIdResolver;
      var _createEntityId2 = createEntityId(entityIdResolver, params, href, path),
        entityId = _createEntityId2.entityId;
      if (entityId != null) {
        closingActions.push({
          entityId: entityId,
          closeTab: function closeTab(event, executeHandlerOnly) {
            if (executeHandlerOnly === void 0) {
              executeHandlerOnly = false;
            }
            close(event, executeHandlerOnly);
            if (executeHandlerOnly === false) {
              handleChange(null, getNewIndex(index));
            }
          }
        });
      }
    });
    dispatchRedux((0, _navigation.setClosingTabHandlerActions)(moduleName, closingActions));
  }, [dispatchRedux, getNewIndex, handleChange, moduleName, pages]);
  return allTabs;
};
__signature__(MuiBar, "useRef{tabs}\nuseStyles{classes}\nuseHistory{history}\nuseDispatchWithModulesData{dispatch}\nuseDispatch{dispatchRedux}\nuseState{[showSelect, setShowSelect](false)}\nuseState{[showConfirmationModal, setShowConfirmationModal](false)}\nuseState{[currentCloseData, setCurrentCloseData]}\nuseSelector{modifiedTabs}\nuseSelector{tabsWithErrors}\nuseCallback{handleChange}\nuseCallback{getNewIndex}\nuseCallback{resizeHandler}\nuseEffect{}\nuseEffect{}", function () {
  return [useStyles, _reactRouterDom.useHistory, _useDispatchWithModulesData.useDispatchWithModulesData, _reactRedux.useDispatch, _reactRedux.useSelector, _reactRedux.useSelector];
});
__signature__(MuiBar, "useRef{tabs}\nuseStyles{classes}\nuseHistory{history}\nuseDispatchWithModulesData{dispatch}\nuseDispatch{dispatchRedux}\nuseState{[showSelect, setShowSelect](false)}\nuseState{[showConfirmationModal, setShowConfirmationModal](false)}\nuseState{[currentCloseData, setCurrentCloseData]}\nuseSelector{modifiedTabs}\nuseSelector{tabsWithErrors}\nuseCallback{handleChange}\nuseCallback{getNewIndex}\nuseCallback{resizeHandler}\nuseEffect{}\nuseEffect{}", function () {
  return [useStyles, _reactRouterDom.useHistory, _useDispatchWithModulesData.useDispatchWithModulesData, _reactRedux.useDispatch, _reactRedux.useSelector, _reactRedux.useSelector];
});
var _default = MuiBar;
var _default2 = _default;
var _default3 = exports.default = _default2;
;
(function () {
  var reactHotLoader = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default : undefined;
  if (!reactHotLoader) {
    return;
  }
  reactHotLoader.register(useStyles, "useStyles", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.js");
  reactHotLoader.register(TabLink, "TabLink", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.js");
  reactHotLoader.register(createEntityId, "createEntityId", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.js");
  reactHotLoader.register(MuiBar, "MuiBar", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.js");
  reactHotLoader.register(_default, "default", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.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(useStyles, "useStyles", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.js");
  reactHotLoader.register(TabLink, "TabLink", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.js");
  reactHotLoader.register(createEntityId, "createEntityId", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.js");
  reactHotLoader.register(MuiBar, "MuiBar", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.js");
  reactHotLoader.register(_default2, "default", "/home/vsts/work/1/s/src/components/MaterialUI/Navigation/TabBar.js");
})();
;
(function () {
  var leaveModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.leaveModule : undefined;
  leaveModule && leaveModule(module);
})();