"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 _immutable = _interopRequireDefault(require("immutable"));
var _get = _interopRequireDefault(require("lodash/get"));
var _qs = _interopRequireDefault(require("qs"));
var _RelatedRecordButtonBar = _interopRequireDefault(require("./RelatedRecordButtonBar"));
var _RelatedRecordPanelContainer = _interopRequireDefault(require("../../containers/record/RelatedRecordPanelContainer"));
var _RelationEditorContainer = _interopRequireDefault(require("../../containers/record/RelationEditorContainer"));
var _SearchToRelateModalContainer = _interopRequireDefault(require("../../containers/search/SearchToRelateModalContainer"));
var _permissionHelpers = require("../../helpers/permissionHelpers");
var _RelatedRecordBrowser = _interopRequireDefault(require("../../../styles/cspace-ui/RelatedRecordBrowser.css"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 propTypes = {
  cloneCsid: _propTypes.default.string,
  config: _propTypes.default.shape({
    recordTypes: _propTypes.default.object
  }),
  history: _propTypes.default.shape({
    replace: _propTypes.default.func
  }),
  location: _propTypes.default.shape({
    state: _propTypes.default.object
  }),
  isSidebarOpen: _propTypes.default.bool,
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  recordType: _propTypes.default.string,
  vocabulary: _propTypes.default.string,
  csid: _propTypes.default.string,
  primaryRecordData: _propTypes.default.instanceOf(_immutable.default.Map),
  preferredRelatedCsid: _propTypes.default.string,
  relatedCsid: _propTypes.default.string,
  relatedRecordType: _propTypes.default.string,
  deselectItem: _propTypes.default.func,
  workflowState: _propTypes.default.string,
  setPreferredRelatedCsid: _propTypes.default.func,
  onShowRelated: _propTypes.default.func
};
const defaultProps = {
  isSidebarOpen: true
};
const contextTypes = {
  intl: _reactIntl.intlShape
};
class RelatedRecordBrowser extends _react.Component {
  constructor() {
    super();
    this.cloneRelatedRecord = this.cloneRelatedRecord.bind(this);
    this.handleCreateButtonClick = this.handleCreateButtonClick.bind(this);
    this.handleRelateButtonClick = this.handleRelateButtonClick.bind(this);
    this.handleRelatedRecordCreated = this.handleRelatedRecordCreated.bind(this);
    this.handleRelatedRecordClick = this.handleRelatedRecordClick.bind(this);
    this.handleRelatedRecordPanelUnrelated = this.handleRelatedRecordPanelUnrelated.bind(this);
    this.handleModalCancelButtonClick = this.handleModalCancelButtonClick.bind(this);
    this.handleModalCloseButtonClick = this.handleModalCloseButtonClick.bind(this);
    this.handleRelationEditorClose = this.handleRelationEditorClose.bind(this);
    this.handleRelationEditorUnrelated = this.handleRelationEditorUnrelated.bind(this);
    this.handleRelationsCreated = this.handleRelationsCreated.bind(this);
    this.state = {
      isSearchToRelateModalOpen: false
    };
  }
  componentDidMount() {
    this.normalizeRelatedCsid();
  }
  componentDidUpdate(prevProps) {
    const {
      relatedCsid,
      relatedRecordType
    } = this.props;
    const {
      relatedRecordType: prevRelatedRecordType,
      relatedCsid: prevRelatedCsid
    } = prevProps;
    if (relatedCsid !== prevRelatedCsid || relatedRecordType !== prevRelatedRecordType) {
      this.normalizeRelatedCsid();
    }
  }
  handleCreateButtonClick() {
    const {
      history,
      location,
      recordType,
      vocabulary,
      csid,
      relatedRecordType
    } = this.props;
    const path = [recordType, vocabulary, csid, relatedRecordType, 'new'].filter(part => !!part).join('/');
    history.replace({
      pathname: `/record/${path}`,
      state: location.state
    });
  }
  handleRelateButtonClick() {
    this.setState({
      isSearchToRelateModalOpen: true
    });
  }
  handleModalCancelButtonClick() {
    this.closeModal();
  }
  handleModalCloseButtonClick() {
    this.closeModal();
  }
  handleRelationEditorClose() {
    const {
      history,
      location,
      recordType,
      vocabulary,
      csid,
      relatedRecordType,
      setPreferredRelatedCsid
    } = this.props;
    if (setPreferredRelatedCsid) {
      setPreferredRelatedCsid(relatedRecordType, undefined);
    }
    const path = [recordType, vocabulary, csid, relatedRecordType].filter(part => !!part).join('/');
    history.replace({
      pathname: `/record/${path}`,
      state: location.state
    });
  }
  handleRelationEditorUnrelated(subject, object) {
    const {
      deselectItem
    } = this.props;

    // If a record is unrelated in the editor, deselect it in the store, since it will no longer
    // appear in the related records list.

    if (deselectItem) {
      deselectItem(this.getRelatedRecordPanelName(), object.csid);
    }
  }
  handleRelationsCreated() {
    this.closeModal();
  }
  handleRelatedRecordClick(item) {
    const {
      relatedRecordType,
      onShowRelated
    } = this.props;
    if (onShowRelated) {
      const relatedCsid = item.get('csid');
      onShowRelated(relatedRecordType, relatedCsid);
    }

    // Prevent the default action.

    return false;
  }
  handleRelatedRecordCreated(newRecordCsid, isNavigating) {
    if (!isNavigating) {
      const {
        history,
        location,
        recordType,
        vocabulary,
        csid,
        relatedRecordType
      } = this.props;
      const path = [recordType, vocabulary, csid, relatedRecordType, newRecordCsid].filter(part => !!part).join('/');
      history.replace({
        pathname: `/record/${path}`,
        state: location.state
      });
    }
  }
  handleRelatedRecordPanelUnrelated(objects) {
    const {
      relatedCsid
    } = this.props;
    let isRelatedCsidUnrelated = false;
    for (let i = 0; i < objects.length; i += 1) {
      if (objects[i].csid === relatedCsid) {
        isRelatedCsidUnrelated = true;
        break;
      }
    }
    if (isRelatedCsidUnrelated) {
      this.handleRelationEditorClose();
    }
  }
  getRelatedRecordPanelName() {
    const {
      relatedRecordType
    } = this.props;
    return `relatedRecordBrowser-${relatedRecordType}`;
  }
  normalizeRelatedCsid() {
    const {
      preferredRelatedCsid,
      relatedCsid,
      relatedRecordType,
      setPreferredRelatedCsid
    } = this.props;
    if (typeof relatedCsid !== 'undefined') {
      if (setPreferredRelatedCsid && preferredRelatedCsid !== relatedCsid) {
        setPreferredRelatedCsid(relatedRecordType, relatedCsid);
      }
    } else if (preferredRelatedCsid) {
      const {
        recordType,
        vocabulary,
        csid,
        history,
        location
      } = this.props;
      const path = [recordType, vocabulary, csid, relatedRecordType, preferredRelatedCsid].filter(part => !!part).join('/');
      history.replace({
        pathname: `/record/${path}`,
        state: location.state
      });
    }
  }
  cloneRelatedRecord(relatedRecordCsid) {
    const {
      recordType,
      vocabulary,
      csid,
      relatedRecordType,
      history,
      location
    } = this.props;
    const path = [recordType, vocabulary, csid, relatedRecordType].filter(part => !!part).join('/');
    const query = {
      clone: relatedRecordCsid
    };
    const queryString = _qs.default.stringify(query);
    history.replace({
      pathname: `/record/${path}/new`,
      search: `?${queryString}`,
      state: location.state
    });
  }
  closeModal() {
    this.setState({
      isSearchToRelateModalOpen: false
    });
  }
  renderRelationEditor() {
    const {
      cloneCsid,
      config,
      recordType,
      csid,
      perms,
      relatedCsid,
      relatedRecordType,
      workflowState
    } = this.props;
    if (typeof relatedCsid === 'undefined' || relatedCsid === null) {
      return null;
    }
    return /*#__PURE__*/_react.default.createElement(_RelationEditorContainer.default, {
      cloneCsid: cloneCsid,
      config: config,
      perms: perms,
      subject: {
        csid,
        recordType
      },
      subjectWorkflowState: workflowState,
      object: {
        csid: relatedCsid,
        recordType: relatedRecordType
      },
      predicate: "affects",
      cloneRecord: this.cloneRelatedRecord,
      onClose: this.handleRelationEditorClose,
      onRecordCreated: this.handleRelatedRecordCreated,
      onUnrelated: this.handleRelationEditorUnrelated
    });
  }
  renderSearchToRelateModal() {
    const {
      config,
      recordType,
      csid,
      relatedRecordType,
      primaryRecordData
    } = this.props;
    const {
      intl
    } = this.context;
    const {
      isSearchToRelateModalOpen
    } = this.state;
    const titleGetter = (0, _get.default)(config, ['recordTypes', recordType, 'title']);
    const title = titleGetter && titleGetter(primaryRecordData, {
      config,
      intl
    });
    return /*#__PURE__*/_react.default.createElement(_SearchToRelateModalContainer.default, {
      subjects: [{
        csid,
        recordType,
        title
      }],
      config: config,
      isOpen: isSearchToRelateModalOpen,
      defaultRecordTypeValue: relatedRecordType,
      onCancelButtonClick: this.handleModalCancelButtonClick,
      onCloseButtonClick: this.handleModalCloseButtonClick,
      onRelationsCreated: this.handleRelationsCreated
    });
  }
  render() {
    const {
      config,
      recordType,
      csid,
      isSidebarOpen,
      perms,
      relatedRecordType,
      workflowState
    } = this.props;
    const isCreatable = (0, _permissionHelpers.canCreate)(relatedRecordType, perms);
    const isRelatable = workflowState !== 'locked' && (0, _permissionHelpers.canRelate)(recordType, perms, config) && (0, _permissionHelpers.canRelate)(relatedRecordType, perms, config);
    const className = isSidebarOpen ? _RelatedRecordBrowser.default.normal : _RelatedRecordBrowser.default.full;

    // TODO: Vary the name of the RelatedRecordPanelContainer depending on the object record type?
    // This would allow selected items to be remembered when switching back and forth between
    // secondary tabs, instead of being cleared.

    return /*#__PURE__*/_react.default.createElement("div", {
      className: className
    }, /*#__PURE__*/_react.default.createElement("header", null, /*#__PURE__*/_react.default.createElement(_RelatedRecordButtonBar.default, {
      isCreatable: isCreatable,
      isRelatable: isRelatable,
      onCreateButtonClick: this.handleCreateButtonClick,
      onRelateButtonClick: this.handleRelateButtonClick
    })), /*#__PURE__*/_react.default.createElement(_RelatedRecordPanelContainer.default, {
      collapsed: false,
      csid: csid,
      config: config,
      linkItems: false,
      name: this.getRelatedRecordPanelName(),
      perms: perms,
      recordType: recordType,
      relatedRecordType: relatedRecordType,
      showCheckboxColumn: isRelatable,
      onItemClick: this.handleRelatedRecordClick,
      onUnrelated: this.handleRelatedRecordPanelUnrelated
    }), this.renderRelationEditor(), this.renderSearchToRelateModal());
  }
}
exports.default = RelatedRecordBrowser;
RelatedRecordBrowser.propTypes = propTypes;
RelatedRecordBrowser.defaultProps = defaultProps;
RelatedRecordBrowser.contextTypes = contextTypes;