"use strict";

exports.__esModule = true;
exports.default = exports.TabLink = void 0;

var _react = _interopRequireDefault(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(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

(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 _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 _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 _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, 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 = _react.default.forwardRef(function (props, ref) {
  return /*#__PURE__*/_react.default.createElement(_reactRouterDom.Link, _extends({
    to: props.to
  }, props, {
    ref: ref
  }), props.children, props.close);
});

exports.TabLink = TabLink;

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 = function handleChange(_, value) {
    if (typeof value === "number" && value >= 0 && value < pages.length) {
      var href = pages[value].href;
      history.push(href);
    } else {
      history.push(module.href);
    }
  };

  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 = function getNewIndex(oldIndex) {
    var newIndex = oldIndex + 1 >= tabLabels.length ? oldIndex - 1 : oldIndex + 1;
    return newIndex;
  };

  var tabCloseHandler = function tabCloseHandler(event, closeCallback, isModified, href, path, entityIdKey, entityId, index) {
    event.stopPropagation();
    event.preventDefault();

    if (isModified) {
      setCurrentCloseData({
        closeCallback: closeCallback,
        href: href,
        path: path,
        entityIdKey: entityIdKey,
        entityId: entityId,
        index: index
      });
      setShowConfirmationModal(true);
    } else {
      closeCallback();
      removeEditState(href, entityIdKey, entityId, path);
      handleChange(null, getNewIndex(index));
    }
  };

  var closeTab = function closeTab() {
    setShowConfirmationModal(false);
    currentCloseData.closeCallback();
    removeEditState(currentCloseData.href, currentCloseData.entityIdKey, currentCloseData.entityId, currentCloseData.path);
    handleChange(null, getNewIndex(currentCloseData.index));
  };

  var removeEditState = function removeEditState(href, entityIdKey, resolvedEntityId, path) {
    if (resolvedEntityId) {
      dispatch(_view2.removeEditNode, [resolvedEntityId]);
      return;
    }

    var newKey = (0, _urlHelper.tryGetNewEntityIdKey)(href);
    var key = entityIdKey === newKey ? entityIdKey : ":".concat(entityIdKey);
    var entityId = (0, _urlHelper.getValueFromUrlByKey)(href, path, key);
    dispatch(_view2.removeEditNode, [entityId]);
  };

  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]);

  _react.default.useEffect(function () {
    var _module$closingTabHan;

    if ((_module$closingTabHan = module.closingTabHandler) != null && _module$closingTabHan.entitySelector) {
      var actions = pages.map(function (p) {
        var _module$closingTabHan2, _module$closingTabHan3;

        return {
          entityId: (_module$closingTabHan2 = (_module$closingTabHan3 = module.closingTabHandler.entitySelector(p.params)) == null ? void 0 : _module$closingTabHan3.entityId) != null ? _module$closingTabHan2 : null,
          closeTab: p.close
        };
      }).filter(function (x) {
        return x.entityId != null;
      });
      dispatchRedux((0, _navigation.setClosingTabHandlerActions)(moduleName, actions));
    }
  }, [dispatchRedux, moduleName, pages, module.closingTabHandler]);

  return /*#__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 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
      }
    }) : null;
    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);
    }
  }));
};

__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{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{resizeHandler}\nuseEffect{}\nuseEffect{}", function () {
  return [useStyles, _reactRouterDom.useHistory, _useDispatchWithModulesData.useDispatchWithModulesData, _reactRedux.useDispatch, _reactRedux.useSelector, _reactRedux.useSelector];
});

var _default = MuiBar;
var _default2 = _default;
var _default3 = _default2;
exports.default = _default3;
;

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