'use strict';

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

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

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _get2 = _interopRequireDefault(_get);

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

const 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,
  primaryRecordData: _propTypes2.default.instanceOf(_immutable2.default.Map),
  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
};

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) {
    var _props = this.props;
    const relatedCsid = _props.relatedCsid,
          relatedRecordType = _props.relatedRecordType;
    const prevRelatedRecordType = prevProps.relatedRecordType,
          prevRelatedCsid = prevProps.relatedCsid;


    if (relatedCsid !== prevRelatedCsid || relatedRecordType !== prevRelatedRecordType) {
      this.normalizeRelatedCsid();
    }
  }

  getRelatedRecordPanelName() {
    const relatedRecordType = this.props.relatedRecordType;


    return `relatedRecordBrowser-${relatedRecordType}`;
  }

  normalizeRelatedCsid() {
    var _props2 = this.props;
    const 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;
      const recordType = _props3.recordType,
            vocabulary = _props3.vocabulary,
            csid = _props3.csid,
            history = _props3.history,
            location = _props3.location;


      const path = [recordType, vocabulary, csid, relatedRecordType, preferredRelatedCsid].filter(part => !!part).join('/');

      history.replace({
        pathname: `/record/${path}`,
        state: location.state
      });
    }
  }

  cloneRelatedRecord(relatedRecordCsid) {
    var _props4 = this.props;
    const recordType = _props4.recordType,
          vocabulary = _props4.vocabulary,
          csid = _props4.csid,
          relatedRecordType = _props4.relatedRecordType,
          history = _props4.history,
          location = _props4.location;


    const path = [recordType, vocabulary, csid, relatedRecordType].filter(part => !!part).join('/');

    const query = {
      clone: relatedRecordCsid
    };

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

    history.replace({
      pathname: `/record/${path}/new`,
      search: `?${queryString}`,
      state: location.state
    });
  }

  closeModal() {
    this.setState({
      isSearchToRelateModalOpen: false
    });
  }

  handleCreateButtonClick() {
    var _props5 = this.props;
    const history = _props5.history,
          location = _props5.location,
          recordType = _props5.recordType,
          vocabulary = _props5.vocabulary,
          csid = _props5.csid,
          relatedRecordType = _props5.relatedRecordType;


    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() {
    var _props6 = this.props;
    const 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);
    }

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

  handleRelationsCreated() {
    this.closeModal();
  }

  handleRelatedRecordClick(item) {
    var _props7 = this.props;
    const relatedRecordType = _props7.relatedRecordType,
          onShowRelated = _props7.onShowRelated;


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

      onShowRelated(relatedRecordType, relatedCsid);
    }

    // Prevent the default action.

    return false;
  }

  handleRelatedRecordCreated(newRecordCsid, isNavigating) {
    if (!isNavigating) {
      var _props8 = this.props;
      const history = _props8.history,
            location = _props8.location,
            recordType = _props8.recordType,
            vocabulary = _props8.vocabulary,
            csid = _props8.csid,
            relatedRecordType = _props8.relatedRecordType;


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


    let isRelatedCsidUnrelated = false;

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

    if (isRelatedCsidUnrelated) {
      this.handleRelationEditorClose();
    }
  }

  renderRelationEditor() {
    var _props9 = this.props;
    const 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,
        recordType
      },
      subjectWorkflowState: workflowState,
      object: {
        csid: relatedCsid,
        recordType: relatedRecordType
      },
      predicate: 'affects',
      cloneRecord: this.cloneRelatedRecord,
      onClose: this.handleRelationEditorClose,
      onRecordCreated: this.handleRelatedRecordCreated,
      onUnrelated: this.handleRelationEditorUnrelated
    });
  }

  renderSearchToRelateModal() {
    var _props10 = this.props;
    const config = _props10.config,
          recordType = _props10.recordType,
          csid = _props10.csid,
          relatedRecordType = _props10.relatedRecordType,
          primaryRecordData = _props10.primaryRecordData;
    const intl = this.context.intl;
    const isSearchToRelateModalOpen = this.state.isSearchToRelateModalOpen;


    const titleGetter = (0, _get2.default)(config, ['recordTypes', recordType, 'title']);
    const title = titleGetter && titleGetter(primaryRecordData, { config, intl });

    return _react2.default.createElement(_SearchToRelateModalContainer2.default, {
      subjects: [{ csid, recordType, title }],
      config: config,
      isOpen: isSearchToRelateModalOpen,
      defaultRecordTypeValue: relatedRecordType,
      onCancelButtonClick: this.handleModalCancelButtonClick,
      onCloseButtonClick: this.handleModalCloseButtonClick,
      onRelationsCreated: this.handleRelationsCreated
    });
  }

  render() {
    var _props11 = this.props;
    const config = _props11.config,
          recordType = _props11.recordType,
          csid = _props11.csid,
          perms = _props11.perms,
          relatedRecordType = _props11.relatedRecordType,
          workflowState = _props11.workflowState;


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

exports.default = RelatedRecordBrowser;
RelatedRecordBrowser.propTypes = propTypes;
RelatedRecordBrowser.contextTypes = contextTypes;