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

var _CheckboxInput2 = _interopRequireDefault(_CheckboxInput);

var _configHelpers = require('../../helpers/configHelpers');

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

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

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

var _SearchPanelContainer2 = _interopRequireDefault(_SearchPanelContainer);

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

var _ConfirmRecordUnrelateModal2 = _interopRequireDefault(_ConfirmRecordUnrelateModal);

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

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

const messages = (0, _reactIntl.defineMessages)({
  title: {
    'id': 'relatedRecordPanel.title',
    'defaultMessage': 'Related {collectionName}'
  }
});

const listType = 'common';

const getSearchDescriptor = props => {
  const csid = props.csid,
        initialSort = props.initialSort,
        recordRelationUpdatedTimestamp = props.recordRelationUpdatedTimestamp,
        relatedRecordType = props.relatedRecordType;


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

const stopPropagation = event => {
  event.stopPropagation();
};

const 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,
  linkItems: _propTypes2.default.bool,
  name: _propTypes2.default.string,
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  recordData: _propTypes2.default.instanceOf(_immutable2.default.Map),
  // These uses aren't detected by eslint.
  /* eslint-disable react/no-unused-prop-types */
  initialSort: _propTypes2.default.string,
  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,
  openModalName: _propTypes2.default.string,
  closeModal: _propTypes2.default.func,
  openModal: _propTypes2.default.func,
  clearSelected: _propTypes2.default.func,
  setAllItemsSelected: _propTypes2.default.func,
  unrelateRecords: _propTypes2.default.func,
  getItemLocation: _propTypes2.default.func,
  onItemClick: _propTypes2.default.func,
  onItemSelectChange: _propTypes2.default.func,
  onUnrelated: _propTypes2.default.func
};

const defaultProps = {
  collapsed: true
};

class RelatedRecordPanel extends _react.Component {
  constructor(props) {
    super(props);

    this.handleCheckboxCommit = this.handleCheckboxCommit.bind(this);
    this.handleConfirmUnrelateButtonClick = this.handleConfirmUnrelateButtonClick.bind(this);
    this.handleModalCancelButtonClick = this.handleModalCancelButtonClick.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.shouldShowCheckbox = this.shouldShowCheckbox.bind(this);

    this.state = {
      isUnrelating: false,
      searchDescriptor: getSearchDescriptor(props)
    };
  }

  componentWillReceiveProps(nextProps) {
    const searchDescriptor = getSearchDescriptor(this.props);

    let 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.

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

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

  shouldShowCheckbox(item) {
    var _props = this.props;
    const config = _props.config,
          perms = _props.perms;


    return item.get('workflowState') !== 'locked' && (0, _permissionHelpers.canUnrelate)((0, _configHelpers.getRecordTypeNameByUri)(config, item.get('uri')), perms, config);
  }

  handleCheckboxCommit(path, value) {
    const index = parseInt(path[0], 10);
    const checked = value;

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


    if (onItemSelectChange) {
      onItemSelectChange(config, name, searchDescriptor, listType, index, checked);
    }
  }

  handleConfirmUnrelateButtonClick() {
    var _props3 = this.props;
    const config = _props3.config,
          csid = _props3.csid,
          name = _props3.name,
          recordType = _props3.recordType,
          relatedRecordType = _props3.relatedRecordType,
          selectedItems = _props3.selectedItems,
          clearSelected = _props3.clearSelected,
          closeModal = _props3.closeModal,
          unrelateRecords = _props3.unrelateRecords,
          onUnrelated = _props3.onUnrelated;


    if (unrelateRecords) {
      this.setState({
        isUnrelating: true
      });

      const subject = {
        csid,
        recordType
      };

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

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

        if (onUnrelated) {
          onUnrelated(objects);
        }

        if (closeModal) {
          closeModal(false);
        }

        this.setState({
          isUnrelating: false
        });
      }).catch(() => {
        this.setState({
          isUnrelating: false
        });
      });
    }
  }

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


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

  handleSearchDescriptorChange(searchDescriptor) {
    this.setState({
      searchDescriptor
    });
  }

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


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

  renderCheckbox({ rowData, rowIndex }) {
    const selectedItems = this.props.selectedItems;


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

      return _react2.default.createElement(_CheckboxInput2.default, {
        embedded: true,
        name: `${rowIndex}`,
        value: selected,
        onCommit: this.handleCheckboxCommit

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

    return null;
  }

  renderConfirmRecordUnrelateModal() {
    var _props4 = this.props;
    const config = _props4.config,
          openModalName = _props4.openModalName,
          relatedRecordType = _props4.relatedRecordType,
          selectedItems = _props4.selectedItems;
    const isUnrelating = this.state.isUnrelating;


    const recordCount = selectedItems ? selectedItems.size : 0;

    return _react2.default.createElement(_ConfirmRecordUnrelateModal2.default, {
      config: config,
      recordType: relatedRecordType,
      isMultiSelect: true,
      isOpen: openModalName === confirmUnrelateModalName,
      isUnrelating: isUnrelating,
      recordCount: recordCount,
      onCancelButtonClick: this.handleModalCancelButtonClick,
      onCloseButtonClick: this.handleModalCancelButtonClick,
      onUnrelateButtonClick: this.handleConfirmUnrelateButtonClick
    });
  }

  renderTableHeader({ searchError, searchResult }) {
    var _props5 = this.props;
    const config = _props5.config,
          name = _props5.name,
          perms = _props5.perms,
          relatedRecordType = _props5.relatedRecordType,
          selectedItems = _props5.selectedItems,
          showCheckboxColumn = _props5.showCheckboxColumn,
          setAllItemsSelected = _props5.setAllItemsSelected;
    const searchDescriptor = this.state.searchDescriptor;


    if (searchError || !showCheckboxColumn || !(0, _permissionHelpers.canUnrelate)(relatedRecordType, perms, config)) {
      return null;
    }

    const selectedCount = selectedItems ? selectedItems.size : 0;

    const 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: this.shouldShowCheckbox
      }),
      this.renderConfirmRecordUnrelateModal()
    );
  }

  renderTitle() {
    var _props6 = this.props;
    const config = _props6.config,
          relatedRecordType = _props6.relatedRecordType;


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

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

    return _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.title, { values: { collectionName } }));
  }

  render() {
    var _props7 = this.props;
    const collapsed = _props7.collapsed,
          color = _props7.color,
          columnSetName = _props7.columnSetName,
          config = _props7.config,
          csid = _props7.csid,
          history = _props7.history,
          linkItems = _props7.linkItems,
          name = _props7.name,
          perms = _props7.perms,
          recordData = _props7.recordData,
          recordType = _props7.recordType,
          relatedRecordType = _props7.relatedRecordType,
          showCheckboxColumn = _props7.showCheckboxColumn,
          showAddButton = _props7.showAddButton,
          getItemLocation = _props7.getItemLocation,
          onItemClick = _props7.onItemClick;
    const searchDescriptor = this.state.searchDescriptor;


    const relatedServiceType = (0, _get2.default)(config, ['recordTypes', relatedRecordType, 'serviceConfig', 'serviceType']);

    if (relatedServiceType === 'object' || relatedServiceType === 'procedure' || relatedServiceType === 'authority') {
      // Don't render if list permissions are not present for the related record type.

      if (!(0, _permissionHelpers.canList)(relatedRecordType, perms)) {
        return null;
      }
    }

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

      return null;
    }

    const renderCheckbox = showCheckboxColumn ? this.renderCheckbox : undefined;

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

exports.default = RelatedRecordPanel;
RelatedRecordPanel.propTypes = propTypes;
RelatedRecordPanel.defaultProps = defaultProps;