'use strict';

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

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 _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var 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}".'
  }
});

var propTypes = {
  cloneCsid: _propTypes2.default.string,
  config: _propTypes2.default.object,
  // 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
  }),
  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),
  predicate: _propTypes2.default.string,
  findResult: _propTypes2.default.instanceOf(_immutable2.default.Map),
  cloneRecord: _propTypes2.default.func,
  createRelation: _propTypes2.default.func,
  findRelation: _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
};

var RelationEditor = function (_Component) {
  _inherits(RelationEditor, _Component);

  function RelationEditor() {
    _classCallCheck(this, RelationEditor);

    var _this = _possibleConstructorReturn(this, (RelationEditor.__proto__ || Object.getPrototypeOf(RelationEditor)).call(this));

    _this.handleCancelButtonClick = _this.handleCancelButtonClick.bind(_this);
    _this.handleCloseButtonClick = _this.handleCloseButtonClick.bind(_this);
    _this.handleUnrelateButtonClick = _this.handleUnrelateButtonClick.bind(_this);
    _this.handleRecordCreated = _this.handleRecordCreated.bind(_this);
    _this.handleRecordTransitioned = _this.handleRecordTransitioned.bind(_this);
    _this.handleSaveCancelled = _this.handleSaveCancelled.bind(_this);
    return _this;
  }

  _createClass(RelationEditor, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.initRelation();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var _props = this.props,
          subject = _props.subject,
          object = _props.object,
          predicate = _props.predicate,
          findResult = _props.findResult;
      var 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();
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      var onUnmount = this.props.onUnmount;


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

      if (onUnmount) {
        onUnmount();
      }
    }
  }, {
    key: 'close',
    value: function close() {
      var onClose = this.props.onClose;


      if (onClose) {
        onClose();
      }
    }
  }, {
    key: 'initRelation',
    value: function initRelation() {
      var _props2 = this.props,
          config = _props2.config,
          subject = _props2.subject,
          object = _props2.object,
          predicate = _props2.predicate,
          findRelation = _props2.findRelation;


      if (findRelation && object.csid) {
        findRelation(config, subject, object, predicate);
      }
    }
  }, {
    key: 'unrelate',
    value: function unrelate() {
      var _props3 = this.props,
          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(function () {
          if (onUnrelated) {
            onUnrelated(subject, object, predicate);
          }
        });
      }
    }
  }, {
    key: 'handleCancelButtonClick',
    value: function handleCancelButtonClick() {
      this.close();
    }
  }, {
    key: 'handleCloseButtonClick',
    value: function handleCloseButtonClick() {
      this.close();
    }
  }, {
    key: 'handleUnrelateButtonClick',
    value: function handleUnrelateButtonClick() {
      this.unrelateWhenUnmounted = true;

      this.close();
    }
  }, {
    key: 'handleRecordCreated',
    value: function handleRecordCreated(newRecordCsid, isNavigating) {
      var _props4 = this.props,
          subject = _props4.subject,
          predicate = _props4.predicate,
          createRelation = _props4.createRelation,
          onRecordCreated = _props4.onRecordCreated;


      if (createRelation) {
        var object = {
          csid: newRecordCsid
        };

        return createRelation(subject, object, predicate).then(function () {
          return onRecordCreated ? onRecordCreated(newRecordCsid, isNavigating) : null;
        });
      }

      return null;
    }
  }, {
    key: 'handleRecordTransitioned',
    value: function handleRecordTransitioned(transitionName) {
      var onRecordTransitioned = this.props.onRecordTransitioned;


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

      if (onRecordTransitioned) {
        onRecordTransitioned(transitionName);
      }
    }
  }, {
    key: 'handleSaveCancelled',
    value: function handleSaveCancelled() {
      this.unrelateWhenUnmounted = false;
    }
  }, {
    key: 'renderHeader',
    value: function renderHeader() {
      var _props5 = this.props,
          config = _props5.config,
          subjectWorkflowState = _props5.subjectWorkflowState,
          object = _props5.object,
          objectData = _props5.objectData;


      var recordTypeConfig = config.recordTypes[object.recordType];

      var cspaceDocument = objectData ? objectData.get(_recordDataHelpers.DOCUMENT_PROPERTY_NAME) : undefined;
      var recordTitle = recordTypeConfig.title(cspaceDocument);

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

      var values = {
        recordTypeName: recordTypeName
      };

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

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

      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, {
            subjectWorkflowState: subjectWorkflowState,
            object: object,
            objectWorkflowState: objectWorkflowState,
            onCancelButtonClick: this.handleCancelButtonClick,
            onCloseButtonClick: this.handleCloseButtonClick,
            onUnrelateButtonClick: this.handleUnrelateButtonClick
          })
        )
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _props6 = this.props,
          cloneRecord = _props6.cloneRecord,
          cloneCsid = _props6.cloneCsid,
          config = _props6.config,
          subject = _props6.subject,
          subjectWorkflowState = _props6.subjectWorkflowState,
          object = _props6.object,
          objectError = _props6.objectError,
          findResult = _props6.findResult;


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

        var isObjectFound = true;

        if (objectError) {
          isObjectFound = false;
        } else {
          // FIXME: Services should return a consistent (or no) namespace prefix.

          var list = findResult.get('ns2:relations-common-list') || findResult.get('ns3:relations-common-list');
          var 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
        })
      );
    }
  }]);

  return RelationEditor;
}(_react.Component);

exports.default = RelationEditor;


RelationEditor.propTypes = propTypes;