"use strict";

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

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

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

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

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

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

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

var _RelationButtonBar = _interopRequireDefault(require("./RelationButtonBar"));

var _WorkflowStateIcon = _interopRequireDefault(require("./WorkflowStateIcon"));

var _RecordEditorContainer = _interopRequireDefault(require("../../containers/record/RecordEditorContainer"));

var _ConfirmRecordUnrelateModal = _interopRequireDefault(require("./ConfirmRecordUnrelateModal"));

var _modalNames = require("../../constants/modalNames");

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

var _recordDataHelpers = require("../../helpers/recordDataHelpers");

var _RelationEditor = _interopRequireDefault(require("../../../styles/cspace-ui/RelationEditor.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; }

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

const confirmUnrelateModalName = `RelationEditor-${_modalNames.MODAL_CONFIRM_RECORD_UNRELATE}`;
exports.confirmUnrelateModalName = confirmUnrelateModalName;
const messages = (0, _reactIntl.defineMessages)({
  editTitle: {
    "id": "relationEditor.editTitle",
    "defaultMessage": "Related {recordTypeName}"
  },
  newTitle: {
    "id": "relationEditor.newTitle",
    "defaultMessage": "New Related {recordTypeName}"
  },
  notFound: {
    "id": "relationEditor.notFound",
    "defaultMessage": "Not Found"
  },
  noRelation: {
    "id": "relationEditor.noRelation",
    "defaultMessage": "There is no related record with CSID \"{csid}\" and type \"{recordType}\"."
  }
});
const propTypes = {
  cloneCsid: _propTypes.default.string,
  config: _propTypes.default.shape({
    recordTypes: _propTypes.default.object
  }),
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  // TODO: These uses aren't properly detected. Try updating eslint-plugin-react.

  /* eslint-disable react/no-unused-prop-types */
  subject: _propTypes.default.shape({
    csid: _propTypes.default.string,
    recordType: _propTypes.default.string
  }),
  subjectWorkflowState: _propTypes.default.string,
  object: _propTypes.default.shape({
    csid: _propTypes.default.string,
    recordType: _propTypes.default.string
  }),

  /* eslint-enable react/no-unused-prop-types */
  objectData: _propTypes.default.instanceOf(_immutable.default.Map),
  objectError: _propTypes.default.instanceOf(_immutable.default.Map),
  openModalName: _propTypes.default.string,
  predicate: _propTypes.default.string,
  findResult: _propTypes.default.instanceOf(_immutable.default.Map),
  cloneRecord: _propTypes.default.func,
  createRelation: _propTypes.default.func,
  findRelation: _propTypes.default.func,
  closeModal: _propTypes.default.func,
  openModal: _propTypes.default.func,
  unrelate: _propTypes.default.func,
  onClose: _propTypes.default.func,
  onRecordCreated: _propTypes.default.func,
  onRecordTransitioned: _propTypes.default.func,
  onUnmount: _propTypes.default.func,
  onUnrelated: _propTypes.default.func
};
const contextTypes = {
  intl: _reactIntl.intlShape
};

class RelationEditor extends _react.Component {
  constructor() {
    super();
    this.handleCancelButtonClick = this.handleCancelButtonClick.bind(this);
    this.handleCloseButtonClick = this.handleCloseButtonClick.bind(this);
    this.handleConfirmUnrelateButtonClick = this.handleConfirmUnrelateButtonClick.bind(this);
    this.handleUnrelateButtonClick = this.handleUnrelateButtonClick.bind(this);
    this.handleModalCancelButtonClick = this.handleModalCancelButtonClick.bind(this);
    this.handleRecordCreated = this.handleRecordCreated.bind(this);
    this.handleRecordTransitioned = this.handleRecordTransitioned.bind(this);
    this.handleSaveCancelled = this.handleSaveCancelled.bind(this);
  }

  componentDidMount() {
    this.initRelation();
  }

  componentDidUpdate(prevProps) {
    const {
      subject,
      object,
      predicate,
      findResult
    } = this.props;
    const {
      subject: prevSubject,
      object: prevObject,
      predicate: prevPredicate,
      findResult: prevFindResult
    } = prevProps;

    if (!(0, _isEqual.default)(subject, prevSubject) || !(0, _isEqual.default)(object, prevObject) || predicate !== prevPredicate || !findResult && prevFindResult) {
      this.initRelation();
    }
  }

  componentWillUnmount() {
    const {
      onUnmount
    } = this.props;

    if (this.unrelateWhenUnmounted) {
      this.unrelate();
    }

    if (onUnmount) {
      onUnmount();
    }
  }

  close() {
    const {
      onClose
    } = this.props;

    if (onClose) {
      onClose();
    }
  }

  initRelation() {
    const {
      config,
      subject,
      object,
      predicate,
      findRelation
    } = this.props;

    if (findRelation && object.csid) {
      findRelation(config, subject, object, predicate);
    }
  }

  unrelate() {
    const {
      config,
      subject,
      object,
      predicate,
      unrelate,
      onUnrelated
    } = this.props;

    if (unrelate) {
      unrelate(config, subject, object, predicate).then(() => {
        if (onUnrelated) {
          onUnrelated(subject, object, predicate);
        }
      });
    }
  }

  handleCancelButtonClick() {
    this.close();
  }

  handleCloseButtonClick() {
    this.close();
  }

  handleConfirmUnrelateButtonClick() {
    const {
      closeModal
    } = this.props;

    if (closeModal) {
      closeModal(false);
    }

    this.unrelateWhenUnmounted = true;
    this.close();
  }

  handleModalCancelButtonClick() {
    const {
      closeModal
    } = this.props;

    if (closeModal) {
      closeModal(false);
    }
  }

  handleUnrelateButtonClick() {
    const {
      openModal
    } = this.props;

    if (openModal) {
      openModal(confirmUnrelateModalName);
    }
  }

  handleRecordCreated(newRecordCsid, isNavigating) {
    const {
      subject,
      predicate,
      createRelation,
      onRecordCreated
    } = this.props;

    if (createRelation) {
      const object = {
        csid: newRecordCsid
      };
      return createRelation(subject, object, predicate).then(() => onRecordCreated ? onRecordCreated(newRecordCsid, isNavigating) : null);
    }

    return null;
  }

  handleRecordTransitioned(transitionName) {
    const {
      onRecordTransitioned
    } = this.props;

    if (transitionName === 'delete') {
      this.close();
    }

    if (onRecordTransitioned) {
      onRecordTransitioned(transitionName);
    }
  }

  handleSaveCancelled() {
    // This handles unrelating an unsaved record. The confirm navigation dialog will be shown, and
    // if it's cancelled, we shouldn't unrelate.
    this.unrelateWhenUnmounted = false;
  }

  renderHeader() {
    const {
      config,
      perms,
      subject,
      subjectWorkflowState,
      object,
      objectData
    } = this.props;
    const {
      intl
    } = this.context;
    const recordTypeConfig = config.recordTypes[object.recordType];
    const recordTitle = recordTypeConfig.title(objectData, {
      config,
      intl
    });

    const recordTypeName = /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, (0, _get.default)(recordTypeConfig, ['messages', 'record', 'name']));

    const values = {
      recordTypeName
    };
    const title = object.csid ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.editTitle, {
      values: values
    })) : /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.newTitle, {
      values: values
    }));
    const objectWorkflowState = (0, _recordDataHelpers.getWorkflowState)(objectData);

    const objectWorkflowStateIcon = /*#__PURE__*/_react.default.createElement(_WorkflowStateIcon.default, {
      value: objectWorkflowState
    });

    const isUnrelatable = subjectWorkflowState !== 'locked' && objectWorkflowState !== 'locked' && (0, _permissionHelpers.canUnrelate)(subject.recordType, perms, config) && (0, _permissionHelpers.canUnrelate)(object.recordType, perms, config);
    return /*#__PURE__*/_react.default.createElement("header", null, /*#__PURE__*/_react.default.createElement("h3", null, title), /*#__PURE__*/_react.default.createElement("div", null, objectWorkflowStateIcon, /*#__PURE__*/_react.default.createElement("h1", null, recordTitle), /*#__PURE__*/_react.default.createElement(_RelationButtonBar.default, {
      isUnrelatable: isUnrelatable,
      object: object,
      onCancelButtonClick: this.handleCancelButtonClick,
      onCloseButtonClick: this.handleCloseButtonClick,
      onUnrelateButtonClick: this.handleUnrelateButtonClick
    })));
  }

  renderConfirmRecordUnrelateModal() {
    const {
      config,
      object,
      objectData,
      openModalName
    } = this.props;
    return /*#__PURE__*/_react.default.createElement(_ConfirmRecordUnrelateModal.default, {
      config: config,
      recordType: object.recordType,
      data: objectData,
      isOpen: openModalName === confirmUnrelateModalName,
      onCancelButtonClick: this.handleModalCancelButtonClick,
      onCloseButtonClick: this.handleModalCancelButtonClick,
      onUnrelateButtonClick: this.handleConfirmUnrelateButtonClick
    });
  }

  render() {
    const {
      cloneRecord,
      cloneCsid,
      config,
      subject,
      subjectWorkflowState,
      object,
      objectError,
      findResult
    } = this.props;

    if (object.csid) {
      if (!findResult) {
        return null;
      }

      let isObjectFound = true;

      if (objectError) {
        isObjectFound = false;
      } else {
        const list = findResult.get('rel:relations-common-list');
        const count = parseInt(list.get('totalItems'), 10);

        if (Number.isNaN(count) || count < 1) {
          isObjectFound = false;
        }
      }

      if (!isObjectFound) {
        // There is no related object record.
        return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("h1", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.notFound)), /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.noRelation, {
          values: {
            csid: object.csid,
            recordType: object.recordType
          }
        }))));
      }
    }

    return /*#__PURE__*/_react.default.createElement("div", {
      className: _RelationEditor.default.common
    }, this.renderHeader(), /*#__PURE__*/_react.default.createElement(_RecordEditorContainer.default, {
      cloneCsid: cloneCsid,
      config: config,
      csid: object.csid,
      recordType: object.recordType,
      relatedSubjectCsid: subject.csid,
      relatedSubjectWorkflowState: subjectWorkflowState,
      clone: cloneRecord,
      onRecordCreated: this.handleRecordCreated,
      onRecordTransitioned: this.handleRecordTransitioned,
      onSaveCancelled: this.handleSaveCancelled
    }), this.renderConfirmRecordUnrelateModal());
  }

}

exports.default = RelationEditor;
RelationEditor.propTypes = propTypes;
RelationEditor.contextTypes = contextTypes;