'use strict';

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

var _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; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _isEqual = require('lodash/isEqual');

var _isEqual2 = _interopRequireDefault(_isEqual);

var _RelationButtonBar = require('./RelationButtonBar');

var _RelationButtonBar2 = _interopRequireDefault(_RelationButtonBar);

var _WorkflowStateIcon = require('./WorkflowStateIcon');

var _WorkflowStateIcon2 = _interopRequireDefault(_WorkflowStateIcon);

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

var _RecordEditorContainer2 = _interopRequireDefault(_RecordEditorContainer);

var _ConfirmRecordUnrelateModal = require('./ConfirmRecordUnrelateModal');

var _ConfirmRecordUnrelateModal2 = _interopRequireDefault(_ConfirmRecordUnrelateModal);

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

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

var _RelationEditor = require('../../../styles/cspace-ui/RelationEditor.css');

var _RelationEditor2 = _interopRequireDefault(_RelationEditor);

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

const confirmUnrelateModalName = exports.confirmUnrelateModalName = `RelationEditor-${_ConfirmRecordUnrelateModal2.default.modalName}`;

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: _propTypes2.default.string,
  config: _propTypes2.default.object,
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  // TODO: These uses aren't properly detected. Try updating eslint-plugin-react.
  /* eslint-disable react/no-unused-prop-types */
  subject: _propTypes2.default.shape({
    csid: _propTypes2.default.string,
    recordType: _propTypes2.default.string
  }),
  subjectWorkflowState: _propTypes2.default.string,
  object: _propTypes2.default.shape({
    csid: _propTypes2.default.string,
    recordType: _propTypes2.default.string
  }),
  /* eslint-enable react/no-unused-prop-types */
  objectData: _propTypes2.default.instanceOf(_immutable2.default.Map),
  objectError: _propTypes2.default.instanceOf(_immutable2.default.Map),
  openModalName: _propTypes2.default.string,
  predicate: _propTypes2.default.string,
  findResult: _propTypes2.default.instanceOf(_immutable2.default.Map),
  cloneRecord: _propTypes2.default.func,
  createRelation: _propTypes2.default.func,
  findRelation: _propTypes2.default.func,
  closeModal: _propTypes2.default.func,
  openModal: _propTypes2.default.func,
  unrelate: _propTypes2.default.func,
  onClose: _propTypes2.default.func,
  onRecordCreated: _propTypes2.default.func,
  onRecordTransitioned: _propTypes2.default.func,
  onUnmount: _propTypes2.default.func,
  onUnrelated: _propTypes2.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) {
    var _props = this.props;
    const subject = _props.subject,
          object = _props.object,
          predicate = _props.predicate,
          findResult = _props.findResult;
    const prevSubject = prevProps.subject,
          prevObject = prevProps.object,
          prevPredicate = prevProps.predicate,
          prevFindResult = prevProps.findResult;


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

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


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

    if (onUnmount) {
      onUnmount();
    }
  }

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


    if (onClose) {
      onClose();
    }
  }

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


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

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


    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.closeModal;


    if (closeModal) {
      closeModal(false);
    }

    this.unrelateWhenUnmounted = true;

    this.close();
  }

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


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

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


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

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


    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.onRecordTransitioned;


    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() {
    var _props5 = this.props;
    const config = _props5.config,
          perms = _props5.perms,
          subject = _props5.subject,
          subjectWorkflowState = _props5.subjectWorkflowState,
          object = _props5.object,
          objectData = _props5.objectData;
    const intl = this.context.intl;


    const recordTypeConfig = config.recordTypes[object.recordType];
    const recordTitle = recordTypeConfig.title(objectData, { config, intl });

    const recordTypeName = _react2.default.createElement(_reactIntl.FormattedMessage, (0, _get2.default)(recordTypeConfig, ['messages', 'record', 'name']));

    const values = {
      recordTypeName
    };

    const title = object.csid ? _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.editTitle, { values: values })) : _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.newTitle, { values: values }));

    const objectWorkflowState = (0, _recordDataHelpers.getWorkflowState)(objectData);
    const objectWorkflowStateIcon = _react2.default.createElement(_WorkflowStateIcon2.default, { value: objectWorkflowState });

    const isUnrelatable = subjectWorkflowState !== 'locked' && objectWorkflowState !== 'locked' && (0, _permissionHelpers.canRelate)(subject.recordType, perms) && (0, _permissionHelpers.canRelate)(object.recordType, perms);

    return _react2.default.createElement(
      'header',
      null,
      _react2.default.createElement(
        'h3',
        null,
        title
      ),
      _react2.default.createElement(
        'div',
        null,
        objectWorkflowStateIcon,
        _react2.default.createElement(
          'h1',
          null,
          recordTitle
        ),
        _react2.default.createElement(_RelationButtonBar2.default, {
          isUnrelatable: isUnrelatable,
          object: object,
          onCancelButtonClick: this.handleCancelButtonClick,
          onCloseButtonClick: this.handleCloseButtonClick,
          onUnrelateButtonClick: this.handleUnrelateButtonClick
        })
      )
    );
  }

  renderConfirmRecordUnrelateModal() {
    var _props6 = this.props;
    const config = _props6.config,
          object = _props6.object,
          objectData = _props6.objectData,
          openModalName = _props6.openModalName;


    return _react2.default.createElement(_ConfirmRecordUnrelateModal2.default, {
      config: config,
      recordType: object.recordType,
      data: objectData,
      isOpen: openModalName === confirmUnrelateModalName,
      onCancelButtonClick: this.handleModalCancelButtonClick,
      onCloseButtonClick: this.handleModalCancelButtonClick,
      onUnrelateButtonClick: this.handleConfirmUnrelateButtonClick
    });
  }

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


    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 (isNaN(count) || count < 1) {
          isObjectFound = false;
        }
      }

      if (!isObjectFound) {
        // There is no related object record.

        return _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(
            'h1',
            null,
            _react2.default.createElement(_reactIntl.FormattedMessage, messages.notFound)
          ),
          _react2.default.createElement(
            'p',
            null,
            _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.noRelation, {
              values: { csid: object.csid, recordType: object.recordType }
            }))
          )
        );
      }
    }

    return _react2.default.createElement(
      'div',
      { className: _RelationEditor2.default.common },
      this.renderHeader(),
      _react2.default.createElement(_RecordEditorContainer2.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;