"use strict";

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

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

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

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

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

var _cspaceLayout = require("cspace-layout");

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

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

var _SearchToSelectModalContainer = _interopRequireDefault(require("../../containers/search/SearchToSelectModalContainer"));

var _RelateButton = _interopRequireDefault(require("../../../styles/cspace-ui/RelateButton.css"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { 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); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

const isSingleSubject = subjects => Array.isArray(subjects) && subjects.length === 1;

const messages = (0, _reactIntl.defineMessages)({
  label: {
    "id": "searchToRelateModal.label",
    "defaultMessage": "Relate records"
  },
  accept: {
    "id": "searchToRelateModal.accept",
    "defaultMessage": "Relate selected"
  },
  relating: {
    "id": "searchToRelateModal.relating",
    "defaultMessage": "Relating\u2026"
  },
  multipleSubjectsRelated: {
    "id": "searchToRelateModal.multipleSubjectsRelated",
    "defaultMessage": "{objectCount, plural, =0 {No records} one {# record} other {# records}} related to each of {subjectCount, number} search results."
  },
  title: {
    "id": "searchToRelateModal.title",
    "defaultMessage": "Relate {typeName} {query}"
  },
  errorTitle: {
    "id": "searchToRelateModal.errorTitle",
    "defaultMessage": "Can't Relate"
  }
});
const errorMessages = (0, _reactIntl.defineMessages)({
  locked: {
    "id": "searchToRelateModal.error.locked",
    "defaultMessage": "Locked records are selected. Relations cannot be made to locked records."
  },
  notPermitted: {
    "id": "searchToRelateModal.error.notPermitted",
    "defaultMessage": "{name} records are selected. You are not permitted to create relations to {collectionName}."
  }
});

const renderRelatingMessage = () => _react.default.createElement("p", null, _react.default.createElement(_reactIntl.FormattedMessage, messages.relating));

const propTypes = {
  config: _propTypes.default.object,
  error: _propTypes.default.object,
  isOpen: _propTypes.default.bool,
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  subjects: _propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.shape({
    /* eslint-disable react/no-unused-prop-types */
    csid: _propTypes.default.string,
    recordType: _propTypes.default.string
    /* eslint-enable react/no-unused-prop-types */

  })), _propTypes.default.func]),
  createRelations: _propTypes.default.func,
  showRelationNotification: _propTypes.default.func,
  onCancelButtonClick: _propTypes.default.func,
  onCloseButtonClick: _propTypes.default.func,
  onRelationsCreated: _propTypes.default.func
};

class SearchToRelateModal extends _react.Component {
  constructor(props) {
    super(props);
    this.customizeSearchDescriptor = this.customizeSearchDescriptor.bind(this);
    this.handleAccept = this.handleAccept.bind(this);
    this.shouldShowCheckbox = this.shouldShowCheckbox.bind(this);
  }

  customizeSearchDescriptor(searchDescriptor) {
    const {
      subjects
    } = this.props;

    if (isSingleSubject(subjects)) {
      return searchDescriptor.setIn(['searchQuery', 'mkRtSbj'], subjects[0].csid);
    }

    return searchDescriptor;
  }

  relate(selectedItems, searchDescriptor) {
    const {
      createRelations,
      onRelationsCreated
    } = this.props;

    if (createRelations) {
      let {
        subjects
      } = this.props;

      if (typeof subjects === 'function') {
        subjects = subjects();
      }

      if (subjects && subjects.length > 0) {
        const objects = selectedItems.valueSeq().map(item => ({
          csid: item.get('csid'),
          recordType: searchDescriptor.get('recordType')
        })).toJS();
        return Promise.all(subjects.map(subject => createRelations(subject, objects, 'affects'))).then(() => {
          if (subjects.length > 1) {
            const {
              showRelationNotification
            } = this.props;

            if (showRelationNotification) {
              showRelationNotification(messages.multipleSubjectsRelated, {
                objectCount: objects.length,
                subjectCount: subjects.length
              });
            }
          }

          if (onRelationsCreated) {
            onRelationsCreated();
          }
        });
      }
    }

    return undefined;
  }

  shouldShowCheckbox(item) {
    if (item.get('workflowState') === 'locked') {
      return false;
    }

    if (item.get('related') === 'true') {
      return false;
    }

    const {
      config,
      perms,
      subjects
    } = this.props;

    if (isSingleSubject(subjects) && item.get('csid') === subjects[0].csid) {
      return false;
    }

    return (0, _permissionHelpers.canRelate)((0, _configHelpers.getRecordTypeNameByUri)(config, item.get('uri')), perms, config);
  }

  handleAccept(selectedItems, searchDescriptor) {
    return this.relate(selectedItems, searchDescriptor);
  }

  render() {
    const _this$props = this.props,
          {
      error,

      /* eslint-disable no-unused-vars */
      subjects,
      createRelations,
      showRelationNotification,
      onRelationsCreated
    } = _this$props,
          remainingProps = _objectWithoutProperties(_this$props, ["error", "subjects", "createRelations", "showRelationNotification", "onRelationsCreated"]);

    if (this.props.isOpen && error) {
      return _react.default.createElement(_cspaceLayout.Modal, {
        isOpen: true,
        showCancelButton: false,
        title: _react.default.createElement("h1", null, _react.default.createElement(_reactIntl.FormattedMessage, messages.errorTitle)),
        onAcceptButtonClick: this.props.onCancelButtonClick,
        onCloseButtonClick: this.props.onCloseButtonClick
      }, _react.default.createElement(_reactIntl.FormattedMessage, _extends({}, errorMessages[error.code], {
        values: error.values
      })));
    }

    return _react.default.createElement(_SearchToSelectModalContainer.default, _extends({
      acceptButtonClassName: _RelateButton.default.common,
      acceptButtonLabel: _react.default.createElement(_reactIntl.FormattedMessage, messages.accept),
      customizeSearchDescriptor: this.customizeSearchDescriptor,
      titleMessage: messages.title,
      renderAcceptPending: renderRelatingMessage,
      shouldShowCheckbox: this.shouldShowCheckbox,
      onAccept: this.handleAccept
    }, remainingProps));
  }

}

exports.default = SearchToRelateModal;
SearchToRelateModal.propTypes = propTypes;