'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 _CheckboxInput = require('cspace-input/lib/components/CheckboxInput');

var _CheckboxInput2 = _interopRequireDefault(_CheckboxInput);

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

var _SearchPanelContainer = require('../../containers/search/SearchPanelContainer');

var _SearchPanelContainer2 = _interopRequireDefault(_SearchPanelContainer);

var _SelectBar = require('../search/SelectBar');

var _SelectBar2 = _interopRequireDefault(_SelectBar);

var _UnrelateButton = require('./UnrelateButton');

var _UnrelateButton2 = _interopRequireDefault(_UnrelateButton);

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)({
  title: {
    'id': 'relatedRecordPanel.title',
    'defaultMessage': 'Related {collectionName}'
  }
});

var listType = 'common';

var getSearchDescriptor = function getSearchDescriptor(props) {
  var csid = props.csid,
      recordRelationUpdatedTimestamp = props.recordRelationUpdatedTimestamp,
      relatedRecordType = props.relatedRecordType;


  return _immutable2.default.fromJS({
    recordType: relatedRecordType,
    searchQuery: {
      rel: csid,
      p: 0,
      size: 5
    },
    seqID: recordRelationUpdatedTimestamp
  });
};

var stopPropagation = function stopPropagation(event) {
  event.stopPropagation();
};

var shouldShowCheckbox = function shouldShowCheckbox(item) {
  var itemWorkflowState = item.get('workflowState');

  if (itemWorkflowState === 'locked') {
    return false;
  }

  return true;
};

var propTypes = {
  collapsed: _propTypes2.default.bool,
  color: _propTypes2.default.string,
  columnSetName: _propTypes2.default.string,
  config: _propTypes2.default.object,
  csid: _propTypes2.default.string,
  history: _propTypes2.default.object,
  name: _propTypes2.default.string,
  recordData: _propTypes2.default.instanceOf(_immutable2.default.Map),
  // This use isn't detected by eslint.
  /* eslint-disable react/no-unused-prop-types */
  recordRelationUpdatedTimestamp: _propTypes2.default.string,
  /* eslint-enable react/no-unused-prop-types */
  recordType: _propTypes2.default.string,
  relatedRecordType: _propTypes2.default.string,
  selectedItems: _propTypes2.default.instanceOf(_immutable2.default.Map),
  showCheckboxColumn: _propTypes2.default.bool,
  showAddButton: _propTypes2.default.bool,
  clearSelected: _propTypes2.default.func,
  setAllItemsSelected: _propTypes2.default.func,
  unrelateRecords: _propTypes2.default.func,
  onItemClick: _propTypes2.default.func,
  onItemSelectChange: _propTypes2.default.func,
  onUnrelated: _propTypes2.default.func
};

var defaultProps = {
  collapsed: true
};

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

  function RelatedRecordPanel(props) {
    _classCallCheck(this, RelatedRecordPanel);

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

    _this.handleCheckboxCommit = _this.handleCheckboxCommit.bind(_this);
    _this.handleSearchDescriptorChange = _this.handleSearchDescriptorChange.bind(_this);
    _this.handleUnrelateButtonClick = _this.handleUnrelateButtonClick.bind(_this);
    _this.renderCheckbox = _this.renderCheckbox.bind(_this);
    _this.renderTableHeader = _this.renderTableHeader.bind(_this);

    _this.state = {
      searchDescriptor: getSearchDescriptor(props)
    };
    return _this;
  }

  _createClass(RelatedRecordPanel, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var searchDescriptor = getSearchDescriptor(this.props);

      var nextSearchDescriptor = getSearchDescriptor(nextProps);

      if (!_immutable2.default.is(searchDescriptor, nextSearchDescriptor)) {
        if (searchDescriptor.get('recordType') === nextSearchDescriptor.get('recordType') && searchDescriptor.getIn(['searchQuery', 'rel']) === nextSearchDescriptor.getIn(['searchQuery', 'rel'])) {
          // The record type and related csid didn't change, so carry over the page number, size, and
          // sort from the current search descriptor.

          var searchQuery = this.state.searchDescriptor.get('searchQuery');

          var nextSearchQuery = nextSearchDescriptor.get('searchQuery').set('p', searchQuery.get('p')).set('size', searchQuery.get('size')).set('sort', searchQuery.get('sort'));

          nextSearchDescriptor = nextSearchDescriptor.set('searchQuery', nextSearchQuery);
        }

        this.setState({
          searchDescriptor: nextSearchDescriptor
        });
      }
    }
  }, {
    key: 'handleCheckboxCommit',
    value: function handleCheckboxCommit(path, value) {
      var index = parseInt(path[0], 10);
      var checked = value;

      var _props = this.props,
          config = _props.config,
          name = _props.name,
          onItemSelectChange = _props.onItemSelectChange;
      var searchDescriptor = this.state.searchDescriptor;


      if (onItemSelectChange) {
        onItemSelectChange(config, name, searchDescriptor, listType, index, checked);
      }
    }
  }, {
    key: 'handleSearchDescriptorChange',
    value: function handleSearchDescriptorChange(searchDescriptor) {
      this.setState({
        searchDescriptor: searchDescriptor
      });
    }
  }, {
    key: 'handleUnrelateButtonClick',
    value: function handleUnrelateButtonClick() {
      var _props2 = this.props,
          config = _props2.config,
          csid = _props2.csid,
          name = _props2.name,
          recordType = _props2.recordType,
          relatedRecordType = _props2.relatedRecordType,
          selectedItems = _props2.selectedItems,
          clearSelected = _props2.clearSelected,
          unrelateRecords = _props2.unrelateRecords,
          onUnrelated = _props2.onUnrelated;


      if (unrelateRecords) {
        var subject = {
          csid: csid,
          recordType: recordType
        };

        var objects = selectedItems.valueSeq().map(function (item) {
          return {
            csid: item.get('csid'),
            recordType: relatedRecordType // TODO: Check the item's docType first
          };
        }).toJS();

        unrelateRecords(config, subject, objects, 'affects').then(function () {
          if (clearSelected) {
            clearSelected(name);
          }

          if (onUnrelated) {
            onUnrelated(objects);
          }
        });
      }
    }
  }, {
    key: 'renderCheckbox',
    value: function renderCheckbox(_ref) {
      var rowData = _ref.rowData,
          rowIndex = _ref.rowIndex;
      var selectedItems = this.props.selectedItems;


      if (shouldShowCheckbox(rowData)) {
        var itemCsid = rowData.get('csid');
        var selected = selectedItems ? selectedItems.has(itemCsid) : false;

        return _react2.default.createElement(_CheckboxInput2.default, {
          name: '' + rowIndex,
          value: selected,
          onCommit: this.handleCheckboxCommit

          // Prevent clicking on the checkbox from selecting the record.
          , onClick: stopPropagation
        });
      }

      return null;
    }
  }, {
    key: 'renderTableHeader',
    value: function renderTableHeader(_ref2) {
      var searchError = _ref2.searchError,
          searchResult = _ref2.searchResult;
      var _props3 = this.props,
          config = _props3.config,
          name = _props3.name,
          selectedItems = _props3.selectedItems,
          showCheckboxColumn = _props3.showCheckboxColumn,
          setAllItemsSelected = _props3.setAllItemsSelected;
      var searchDescriptor = this.state.searchDescriptor;


      if (searchError || !showCheckboxColumn) {
        return null;
      }

      var selectedCount = selectedItems ? selectedItems.size : 0;

      var unrelateButton = _react2.default.createElement(_UnrelateButton2.default, {
        disabled: selectedCount < 1,
        key: 'unrelate',
        name: 'unrelate',
        onClick: this.handleUnrelateButtonClick
      });

      return _react2.default.createElement(
        'header',
        null,
        _react2.default.createElement(_SelectBar2.default, {
          buttons: [unrelateButton],
          config: config,
          listType: listType,
          searchDescriptor: searchDescriptor,
          searchName: name,
          searchResult: searchResult,
          selectedItems: selectedItems,
          setAllItemsSelected: setAllItemsSelected,
          showCheckboxFilter: shouldShowCheckbox
        })
      );
    }
  }, {
    key: 'renderTitle',
    value: function renderTitle() {
      var _props4 = this.props,
          config = _props4.config,
          relatedRecordType = _props4.relatedRecordType;


      var collectionNameMessage = (0, _get2.default)(config, ['recordTypes', relatedRecordType, 'messages', 'record', 'collectionName']);

      var collectionName = _react2.default.createElement(_reactIntl.FormattedMessage, collectionNameMessage);

      return _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.title, { values: { collectionName: collectionName } }));
    }
  }, {
    key: 'render',
    value: function render() {
      var _props5 = this.props,
          collapsed = _props5.collapsed,
          color = _props5.color,
          columnSetName = _props5.columnSetName,
          config = _props5.config,
          csid = _props5.csid,
          history = _props5.history,
          name = _props5.name,
          recordData = _props5.recordData,
          recordType = _props5.recordType,
          showCheckboxColumn = _props5.showCheckboxColumn,
          showAddButton = _props5.showAddButton,
          onItemClick = _props5.onItemClick;
      var searchDescriptor = this.state.searchDescriptor;


      if (!(0, _recordDataHelpers.getUpdatedTimestamp)(recordData)) {
        // Don't render until after the record has loaded.

        return null;
      }

      var renderCheckbox = showCheckboxColumn ? this.renderCheckbox : undefined;

      return _react2.default.createElement(_SearchPanelContainer2.default, {
        collapsed: collapsed,
        color: color,
        columnSetName: columnSetName,
        config: config,
        csid: csid,
        history: history,
        name: name,
        searchDescriptor: searchDescriptor,
        recordType: recordType,
        title: this.renderTitle(),
        showAddButton: showAddButton,
        showCheckboxColumn: showCheckboxColumn,
        renderCheckbox: renderCheckbox,
        renderTableHeader: this.renderTableHeader,
        onItemClick: onItemClick,
        onSearchDescriptorChange: this.handleSearchDescriptorChange
      });
    }
  }]);

  return RelatedRecordPanel;
}(_react.Component);

exports.default = RelatedRecordPanel;


RelatedRecordPanel.propTypes = propTypes;
RelatedRecordPanel.defaultProps = defaultProps;