"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.confirmUnrelateModalName = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _immutable = _interopRequireDefault(require("immutable"));

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

var _get = _interopRequireDefault(require("lodash/get"));

var _CheckboxInput = _interopRequireDefault(require("cspace-input/lib/components/CheckboxInput"));

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

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

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

var _modalNames = require("../../constants/modalNames");

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

var _ConfirmRecordUnrelateModal = _interopRequireDefault(require("./ConfirmRecordUnrelateModal"));

var _SelectBar = _interopRequireDefault(require("../search/SelectBar"));

var _UnrelateButton = _interopRequireDefault(require("./UnrelateButton"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _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; }; return _extends.apply(this, arguments); }

const confirmUnrelateModalName = `RelatedRecordPanel-${_modalNames.MODAL_CONFIRM_RECORD_UNRELATE}`;
exports.confirmUnrelateModalName = confirmUnrelateModalName;
const messages = (0, _reactIntl.defineMessages)({
  title: {
    "id": "relatedRecordPanel.title",
    "defaultMessage": "Related {collectionName}"
  }
});

const getSearchDescriptor = props => {
  const {
    config,
    csid,
    initialSort,
    recordRelationUpdatedTimestamp,
    relatedRecordType
  } = props;
  return _immutable.default.fromJS({
    recordType: relatedRecordType,
    searchQuery: {
      rel: csid,
      relType: 'affects',
      p: 0,
      size: config.defaultSearchPanelSize || 5,
      sort: initialSort
    },
    seqID: recordRelationUpdatedTimestamp
  });
};

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

const propTypes = {
  collapsed: _propTypes.default.bool,
  color: _propTypes.default.string,
  columnSetName: _propTypes.default.string,
  config: _propTypes.default.shape({
    listTypes: _propTypes.default.object
  }),
  csid: _propTypes.default.string,
  listType: _propTypes.default.string,
  linkItems: _propTypes.default.bool,
  name: _propTypes.default.string,
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  recordData: _propTypes.default.instanceOf(_immutable.default.Map),
  // These uses aren't detected by eslint.

  /* eslint-disable react/no-unused-prop-types */
  initialSort: _propTypes.default.string,
  recordRelationUpdatedTimestamp: _propTypes.default.string,

  /* eslint-enable react/no-unused-prop-types */
  recordType: _propTypes.default.string,
  relatedRecordType: _propTypes.default.string,
  selectedItems: _propTypes.default.instanceOf(_immutable.default.Map),
  showCheckboxColumn: _propTypes.default.bool,
  showSearchButton: _propTypes.default.bool,
  showAddButton: _propTypes.default.bool,
  openModalName: _propTypes.default.string,
  closeModal: _propTypes.default.func,
  openModal: _propTypes.default.func,
  clearSelected: _propTypes.default.func,
  setAllItemsSelected: _propTypes.default.func,
  unrelateRecords: _propTypes.default.func,
  getItemLocation: _propTypes.default.func,
  onItemClick: _propTypes.default.func,
  onItemSelectChange: _propTypes.default.func,
  onUnrelated: _propTypes.default.func
};
const defaultProps = {
  collapsed: true,
  listType: 'common'
};

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)
    };
  } // eslint-disable-next-line camelcase


  UNSAFE_componentWillReceiveProps(nextProps) {
    const searchDescriptor = getSearchDescriptor(this.props);
    let nextSearchDescriptor = getSearchDescriptor(nextProps);

    if (!_immutable.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 {
          searchDescriptor: currentSearchDescriptor
        } = this.state;
        const searchQuery = currentSearchDescriptor.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) {
    const {
      config,
      perms
    } = this.props;
    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;
    const {
      config,
      name,
      listType,
      onItemSelectChange
    } = this.props;
    const {
      searchDescriptor
    } = this.state;

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

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

    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;

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

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

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

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

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

    if (this.shouldShowCheckbox(rowData)) {
      const itemCsid = rowData.get('csid');
      const selected = selectedItems ? selectedItems.has(itemCsid) : false;
      return /*#__PURE__*/_react.default.createElement(_CheckboxInput.default, {
        embedded: true,
        name: `${rowIndex}`,
        value: selected,
        onCommit: this.handleCheckboxCommit // Prevent clicking on the checkbox from selecting the record.
        ,
        onClick: stopPropagation
      });
    }

    return null;
  }

  renderConfirmRecordUnrelateModal() {
    const {
      config,
      openModalName,
      relatedRecordType,
      selectedItems
    } = this.props;
    const {
      isUnrelating
    } = this.state;
    const recordCount = selectedItems ? selectedItems.size : 0;
    return /*#__PURE__*/_react.default.createElement(_ConfirmRecordUnrelateModal.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
  }) {
    const {
      config,
      name,
      perms,
      listType,
      relatedRecordType,
      selectedItems,
      showCheckboxColumn,
      setAllItemsSelected
    } = this.props;
    const {
      searchDescriptor
    } = this.state;

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

    const selectedCount = selectedItems ? selectedItems.size : 0;

    const unrelateButton = /*#__PURE__*/_react.default.createElement(_UnrelateButton.default, {
      disabled: selectedCount < 1,
      key: "unrelate",
      name: "unrelate",
      onClick: this.handleUnrelateButtonClick
    });

    return /*#__PURE__*/_react.default.createElement("header", null, /*#__PURE__*/_react.default.createElement(_SelectBar.default, {
      buttons: [unrelateButton],
      config: config,
      listType: listType,
      searchDescriptor: searchDescriptor,
      searchName: name,
      searchResult: searchResult,
      selectedItems: selectedItems,
      setAllItemsSelected: setAllItemsSelected,
      showCheckboxFilter: this.shouldShowCheckbox
    }), this.renderConfirmRecordUnrelateModal());
  }

  renderTitle() {
    const {
      config,
      relatedRecordType
    } = this.props;
    const collectionNameMessage = (0, _get.default)(config, ['recordTypes', relatedRecordType, 'messages', 'record', 'collectionName']);

    const collectionName = /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, collectionNameMessage);

    return /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.title, {
      values: {
        collectionName
      }
    }));
  }

  render() {
    const {
      collapsed,
      color,
      columnSetName,
      config,
      csid,
      listType,
      linkItems,
      name,
      perms,
      recordData,
      recordType,
      relatedRecordType,
      showCheckboxColumn,
      showSearchButton,
      showAddButton,
      getItemLocation,
      onItemClick
    } = this.props;
    const {
      searchDescriptor
    } = this.state;
    const relatedServiceType = (0, _get.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 /*#__PURE__*/_react.default.createElement(_SearchPanelContainer.default, {
      collapsed: collapsed,
      color: color,
      columnSetName: columnSetName,
      config: config,
      csid: csid,
      listType: listType,
      linkItems: linkItems,
      name: name,
      searchDescriptor: searchDescriptor,
      recordType: recordType,
      recordData: recordData,
      title: this.renderTitle(),
      showAddButton: showAddButton,
      showSearchButton: showSearchButton,
      showCheckboxColumn: showCheckboxColumn,
      renderCheckbox: renderCheckbox,
      renderTableHeader: this.renderTableHeader,
      getItemLocation: getItemLocation,
      onItemClick: onItemClick,
      onSearchDescriptorChange: this.handleSearchDescriptorChange
    });
  }

}

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