'use strict';

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

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 _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _RelatedRecordButtonBar = require('./RelatedRecordButtonBar');

var _RelatedRecordButtonBar2 = _interopRequireDefault(_RelatedRecordButtonBar);

var _RelatedRecordPanelContainer = require('../../containers/record/RelatedRecordPanelContainer');

var _RelatedRecordPanelContainer2 = _interopRequireDefault(_RelatedRecordPanelContainer);

var _RelationEditorContainer = require('../../containers/record/RelationEditorContainer');

var _RelationEditorContainer2 = _interopRequireDefault(_RelationEditorContainer);

var _SearchToRelateModalContainer = require('../../containers/search/SearchToRelateModalContainer');

var _SearchToRelateModalContainer2 = _interopRequireDefault(_SearchToRelateModalContainer);

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

var _RelatedRecordBrowser = require('../../../styles/cspace-ui/RelatedRecordBrowser.css');

var _RelatedRecordBrowser2 = _interopRequireDefault(_RelatedRecordBrowser);

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 propTypes = {
  cloneCsid: _propTypes2.default.string,
  config: _propTypes2.default.object,
  history: _propTypes2.default.object,
  location: _propTypes2.default.object,
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  recordType: _propTypes2.default.string,
  vocabulary: _propTypes2.default.string,
  csid: _propTypes2.default.string,
  preferredRelatedCsid: _propTypes2.default.string,
  relatedCsid: _propTypes2.default.string,
  relatedRecordType: _propTypes2.default.string,
  deselectItem: _propTypes2.default.func,
  workflowState: _propTypes2.default.string,
  setPreferredRelatedCsid: _propTypes2.default.func,
  onShowRelated: _propTypes2.default.func
};

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

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

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

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

  _createClass(RelatedRecordBrowser, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.normalizeRelatedCsid();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var _props = this.props,
          relatedCsid = _props.relatedCsid,
          relatedRecordType = _props.relatedRecordType;
      var prevRelatedRecordType = prevProps.relatedRecordType,
          prevRelatedCsid = prevProps.relatedCsid;


      if (relatedCsid !== prevRelatedCsid || relatedRecordType !== prevRelatedRecordType) {
        this.normalizeRelatedCsid();
      }
    }
  }, {
    key: 'getRelatedRecordPanelName',
    value: function getRelatedRecordPanelName() {
      var relatedRecordType = this.props.relatedRecordType;


      return 'relatedRecordBrowser-' + relatedRecordType;
    }
  }, {
    key: 'normalizeRelatedCsid',
    value: function normalizeRelatedCsid() {
      var _props2 = this.props,
          preferredRelatedCsid = _props2.preferredRelatedCsid,
          relatedCsid = _props2.relatedCsid,
          relatedRecordType = _props2.relatedRecordType,
          setPreferredRelatedCsid = _props2.setPreferredRelatedCsid;


      if (typeof relatedCsid !== 'undefined') {
        if (setPreferredRelatedCsid && preferredRelatedCsid !== relatedCsid) {
          setPreferredRelatedCsid(relatedRecordType, relatedCsid);
        }
      } else if (preferredRelatedCsid) {
        var _props3 = this.props,
            recordType = _props3.recordType,
            vocabulary = _props3.vocabulary,
            csid = _props3.csid,
            history = _props3.history,
            location = _props3.location;


        var path = [recordType, vocabulary, csid, relatedRecordType, preferredRelatedCsid].filter(function (part) {
          return !!part;
        }).join('/');

        history.replace({
          pathname: '/record/' + path,
          state: location.state
        });
      }
    }
  }, {
    key: 'cloneRelatedRecord',
    value: function cloneRelatedRecord(relatedRecordCsid) {
      var _props4 = this.props,
          recordType = _props4.recordType,
          vocabulary = _props4.vocabulary,
          csid = _props4.csid,
          relatedRecordType = _props4.relatedRecordType,
          history = _props4.history,
          location = _props4.location;


      var path = [recordType, vocabulary, csid, relatedRecordType].filter(function (part) {
        return !!part;
      }).join('/');

      var query = {
        clone: relatedRecordCsid
      };

      var queryString = _qs2.default.stringify(query);

      history.replace({
        pathname: '/record/' + path + '/new',
        search: '?' + queryString,
        state: location.state
      });
    }
  }, {
    key: 'closeModal',
    value: function closeModal() {
      this.setState({
        isSearchToRelateModalOpen: false
      });
    }
  }, {
    key: 'handleCreateButtonClick',
    value: function handleCreateButtonClick() {
      var _props5 = this.props,
          history = _props5.history,
          location = _props5.location,
          recordType = _props5.recordType,
          vocabulary = _props5.vocabulary,
          csid = _props5.csid,
          relatedRecordType = _props5.relatedRecordType;


      var path = [recordType, vocabulary, csid, relatedRecordType, 'new'].filter(function (part) {
        return !!part;
      }).join('/');

      history.replace({
        pathname: '/record/' + path,
        state: location.state
      });
    }
  }, {
    key: 'handleRelateButtonClick',
    value: function handleRelateButtonClick() {
      this.setState({
        isSearchToRelateModalOpen: true
      });
    }
  }, {
    key: 'handleModalCancelButtonClick',
    value: function handleModalCancelButtonClick() {
      this.closeModal();
    }
  }, {
    key: 'handleModalCloseButtonClick',
    value: function handleModalCloseButtonClick() {
      this.closeModal();
    }
  }, {
    key: 'handleRelationEditorClose',
    value: function handleRelationEditorClose() {
      var _props6 = this.props,
          history = _props6.history,
          location = _props6.location,
          recordType = _props6.recordType,
          vocabulary = _props6.vocabulary,
          csid = _props6.csid,
          relatedRecordType = _props6.relatedRecordType,
          setPreferredRelatedCsid = _props6.setPreferredRelatedCsid;


      if (setPreferredRelatedCsid) {
        setPreferredRelatedCsid(relatedRecordType, undefined);
      }

      var path = [recordType, vocabulary, csid, relatedRecordType].filter(function (part) {
        return !!part;
      }).join('/');

      history.replace({
        pathname: '/record/' + path,
        state: location.state
      });
    }
  }, {
    key: 'handleRelationEditorUnrelated',
    value: function handleRelationEditorUnrelated(subject, object) {
      var deselectItem = this.props.deselectItem;

      // 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);
      }
    }
  }, {
    key: 'handleRelationsCreated',
    value: function handleRelationsCreated() {
      this.closeModal();
    }
  }, {
    key: 'handleRelatedRecordClick',
    value: function handleRelatedRecordClick(item) {
      var _props7 = this.props,
          relatedRecordType = _props7.relatedRecordType,
          onShowRelated = _props7.onShowRelated;


      if (onShowRelated) {
        var relatedCsid = item.get('csid');

        onShowRelated(relatedRecordType, relatedCsid);
      }

      // Prevent the default action.

      return false;
    }
  }, {
    key: 'handleRelatedRecordCreated',
    value: function handleRelatedRecordCreated(newRecordCsid, isNavigating) {
      if (!isNavigating) {
        var _props8 = this.props,
            history = _props8.history,
            location = _props8.location,
            recordType = _props8.recordType,
            vocabulary = _props8.vocabulary,
            csid = _props8.csid,
            relatedRecordType = _props8.relatedRecordType;


        var path = [recordType, vocabulary, csid, relatedRecordType, newRecordCsid].filter(function (part) {
          return !!part;
        }).join('/');

        history.replace({
          pathname: '/record/' + path,
          state: location.state
        });
      }
    }
  }, {
    key: 'handleRelatedRecordPanelUnrelated',
    value: function handleRelatedRecordPanelUnrelated(objects) {
      var relatedCsid = this.props.relatedCsid;


      var isRelatedCsidUnrelated = false;

      for (var i = 0; i < objects.length; i += 1) {
        if (objects[i].csid === relatedCsid) {
          isRelatedCsidUnrelated = true;
          break;
        }
      }

      if (isRelatedCsidUnrelated) {
        this.handleRelationEditorClose();
      }
    }
  }, {
    key: 'renderRelationEditor',
    value: function renderRelationEditor() {
      var _props9 = this.props,
          cloneCsid = _props9.cloneCsid,
          config = _props9.config,
          recordType = _props9.recordType,
          csid = _props9.csid,
          perms = _props9.perms,
          relatedCsid = _props9.relatedCsid,
          relatedRecordType = _props9.relatedRecordType,
          workflowState = _props9.workflowState;


      if (typeof relatedCsid === 'undefined' || relatedCsid === null) {
        return null;
      }

      return _react2.default.createElement(_RelationEditorContainer2.default, {
        cloneCsid: cloneCsid,
        config: config,
        perms: perms,
        subject: {
          csid: csid,
          recordType: recordType
        },
        subjectWorkflowState: workflowState,
        object: {
          csid: relatedCsid,
          recordType: relatedRecordType
        },
        predicate: 'affects',
        cloneRecord: this.cloneRelatedRecord,
        onClose: this.handleRelationEditorClose,
        onRecordCreated: this.handleRelatedRecordCreated,
        onUnrelated: this.handleRelationEditorUnrelated
      });
    }
  }, {
    key: 'renderSearchToRelateModal',
    value: function renderSearchToRelateModal() {
      var _props10 = this.props,
          config = _props10.config,
          recordType = _props10.recordType,
          csid = _props10.csid,
          relatedRecordType = _props10.relatedRecordType;
      var isSearchToRelateModalOpen = this.state.isSearchToRelateModalOpen;


      return _react2.default.createElement(_SearchToRelateModalContainer2.default, {
        subjects: [{ csid: csid, recordType: recordType }],
        config: config,
        isOpen: isSearchToRelateModalOpen,
        defaultRecordTypeValue: relatedRecordType,
        onCancelButtonClick: this.handleModalCancelButtonClick,
        onCloseButtonClick: this.handleModalCloseButtonClick,
        onRelationsCreated: this.handleRelationsCreated
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props11 = this.props,
          config = _props11.config,
          recordType = _props11.recordType,
          csid = _props11.csid,
          perms = _props11.perms,
          relatedRecordType = _props11.relatedRecordType,
          workflowState = _props11.workflowState;


      var isRelatable = workflowState !== 'locked' && (0, _permissionHelpers.canRelate)(recordType, perms) && (0, _permissionHelpers.canRelate)(relatedRecordType, perms);

      // 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 _react2.default.createElement(
        'div',
        { className: _RelatedRecordBrowser2.default.common },
        _react2.default.createElement(
          'header',
          null,
          _react2.default.createElement(_RelatedRecordButtonBar2.default, {
            isRelatable: isRelatable,
            onCreateButtonClick: this.handleCreateButtonClick,
            onRelateButtonClick: this.handleRelateButtonClick
          })
        ),
        _react2.default.createElement(_RelatedRecordPanelContainer2.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()
      );
    }
  }]);

  return RelatedRecordBrowser;
}(_react.Component);

exports.default = RelatedRecordBrowser;


RelatedRecordBrowser.propTypes = propTypes;