"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactIntl = require("react-intl");

var _cspaceInput = require("cspace-input");

var _immutable = _interopRequireDefault(require("immutable"));

var _get = _interopRequireDefault(require("lodash/get"));

var _pickBy = _interopRequireDefault(require("lodash/pickBy"));

var _configHelpers = require("../../helpers/configHelpers");

var _permissionHelpers = require("../../helpers/permissionHelpers");

var _RecordBrowserNavBar = _interopRequireDefault(require("../../../styles/cspace-ui/RecordBrowserNavBar.css"));

var _RecordBrowserNavItem = _interopRequireDefault(require("../../../styles/cspace-ui/RecordBrowserNavItem.css"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 {
  RecordTypeInput
} = _cspaceInput.components;
const messages = (0, _reactIntl.defineMessages)({
  new: {
    "id": "recordBrowserNavBar.new",
    "defaultMessage": "New Record"
  },
  primary: {
    "id": "recordBrowserNavBar.primary",
    "defaultMessage": "Primary Record"
  },
  related: {
    "id": "recordBrowserNavBar.related",
    "defaultMessage": "+ Related"
  },
  moreRelated: {
    "id": "recordBrowserNavBar.moreRelated",
    "defaultMessage": "+ Related"
  },
  close: {
    "id": "recordBrowserNavBar.close",
    "defaultMessage": "close"
  }
});

const filterRecordTypes = (recordTypes, relatedRecordBrowsers, perms) => {
  const existingBrowsers = relatedRecordBrowsers.toOrderedSet();
  return (0, _pickBy.default)(recordTypes, (recordTypeConfig, name) => {
    const serviceType = (0, _get.default)(recordTypeConfig, ['serviceConfig', 'serviceType']);
    return (serviceType === 'procedure' || serviceType === 'object') && !existingBrowsers.includes(name) && (0, _permissionHelpers.canList)(name, perms);
  });
};

const propTypes = {
  config: _propTypes.default.shape({
    recordTypes: _propTypes.default.object
  }),
  csid: _propTypes.default.string,
  recordType: _propTypes.default.string,
  relatedRecordType: _propTypes.default.string,
  intl: _reactIntl.intlShape,
  items: _propTypes.default.instanceOf(_immutable.default.List),
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  setItems: _propTypes.default.func,
  onSelect: _propTypes.default.func
};
const defaultProps = {
  items: _immutable.default.List()
};

class RecordBrowserNavBar extends _react.Component {
  constructor() {
    super();
    this.formatRecordTypeLabel = this.formatRecordTypeLabel.bind(this);
    this.handleItemButtonClick = this.handleItemButtonClick.bind(this);
    this.handleItemCloseButtonClick = this.handleItemCloseButtonClick.bind(this);
    this.handleRecordTypeDropdownCommit = this.handleRecordTypeDropdownCommit.bind(this);
  }

  componentDidMount() {
    this.initItems();
  }

  componentDidUpdate() {
    this.initItems();
  }

  initItems() {
    const {
      recordType,
      relatedRecordType,
      items,
      setItems
    } = this.props;

    if (setItems && relatedRecordType && !items.includes(relatedRecordType)) {
      // We entered a related record page via URL, but there isn't currently a tab open for that
      // record type. Open the tab.
      setItems(recordType, items.push(relatedRecordType));
    }
  }

  formatRecordTypeLabel(name, config) {
    const {
      intl
    } = this.props;
    return intl.formatMessage(config.messages.record.collectionName) || name;
  }

  handleItemButtonClick(event) {
    const {
      onSelect
    } = this.props;

    if (onSelect) {
      const {
        recordtype: relatedRecordType
      } = event.target.dataset;
      onSelect(relatedRecordType);
    }
  }

  handleItemCloseButtonClick(event) {
    const {
      recordType,
      relatedRecordType,
      items,
      setItems,
      onSelect
    } = this.props;
    const {
      recordtype: closedType
    } = event.target.dataset;
    const itemSet = items.toOrderedSet();
    const updatedItems = itemSet.delete(closedType).toList();

    if (setItems) {
      setItems(recordType, updatedItems);
    }

    if (onSelect && closedType === relatedRecordType) {
      let index = itemSet.toList().findKey(value => value === closedType);

      if (index > updatedItems.size - 1) {
        index = updatedItems.size - 1;
      }

      const newType = updatedItems.get(index);
      onSelect(newType);
    }
  }

  handleRecordTypeDropdownCommit(path, value) {
    const {
      recordType,
      items,
      setItems,
      onSelect
    } = this.props;

    if (setItems) {
      const updatedItems = items.toOrderedSet().add(value).toList();
      setItems(recordType, updatedItems);
    }

    if (onSelect) {
      onSelect(value);
    }
  }

  render() {
    const {
      config,
      csid,
      intl,
      items,
      perms,
      recordType,
      relatedRecordType
    } = this.props;
    const recordTypeConfig = (0, _get.default)(config, ['recordTypes', recordType]);
    const showRelatedItems = csid && !(0, _configHelpers.isAuthority)(recordTypeConfig) && !(0, _configHelpers.isUtility)(recordTypeConfig);

    const primaryItem = /*#__PURE__*/_react.default.createElement("li", {
      className: relatedRecordType ? _RecordBrowserNavItem.default.normal : _RecordBrowserNavItem.default.active
    }, /*#__PURE__*/_react.default.createElement("button", {
      disabled: !showRelatedItems || !relatedRecordType,
      type: "button",
      onClick: this.handleItemButtonClick
    }, intl.formatMessage(csid ? messages.primary : messages.new)));

    let relatedItems;

    if (showRelatedItems) {
      relatedItems = _immutable.default.OrderedSet(items).map(itemRecordType => {
        const itemRecordTypeConfig = (0, _get.default)(config, ['recordTypes', itemRecordType]);
        const label = this.formatRecordTypeLabel(itemRecordType, itemRecordTypeConfig);
        const className = itemRecordType === relatedRecordType ? _RecordBrowserNavItem.default.active : _RecordBrowserNavItem.default.normal;
        return /*#__PURE__*/_react.default.createElement("li", {
          className: className,
          key: itemRecordType
        }, /*#__PURE__*/_react.default.createElement("button", {
          "data-recordtype": itemRecordType,
          disabled: itemRecordType === relatedRecordType,
          type: "button",
          onClick: this.handleItemButtonClick
        }, label), /*#__PURE__*/_react.default.createElement("button", {
          "aria-label": intl.formatMessage(messages.close),
          "data-recordtype": itemRecordType,
          type: "button",
          onClick: this.handleItemCloseButtonClick
        }));
      });
    }

    let relatedRecordTypeSelector;

    if (showRelatedItems) {
      const filteredRecordTypes = filterRecordTypes(config.recordTypes, items, perms);

      if (Object.keys(filteredRecordTypes).length > 0) {
        const placeholder = items.size > 0 ? intl.formatMessage(messages.moreRelated) : intl.formatMessage(messages.related);
        relatedRecordTypeSelector = /*#__PURE__*/_react.default.createElement("li", {
          className: _RecordBrowserNavItem.default.selector
        }, /*#__PURE__*/_react.default.createElement(RecordTypeInput, {
          filtering: false,
          indentItems: false,
          placeholder: placeholder,
          recordTypes: filteredRecordTypes,
          value: "0",
          formatRecordTypeLabel: this.formatRecordTypeLabel,
          onCommit: this.handleRecordTypeDropdownCommit
        }));
      }
    }

    const serviceType = (0, _get.default)(config, ['recordTypes', recordType, 'serviceConfig', 'serviceType']);
    return /*#__PURE__*/_react.default.createElement("nav", {
      className: _RecordBrowserNavBar.default[serviceType]
    }, /*#__PURE__*/_react.default.createElement("ul", null, primaryItem, relatedItems, relatedRecordTypeSelector));
  }

}

RecordBrowserNavBar.propTypes = propTypes;
RecordBrowserNavBar.defaultProps = defaultProps;

var _default = (0, _reactIntl.injectIntl)(RecordBrowserNavBar);

exports.default = _default;