"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 _get = _interopRequireDefault(require("lodash/get"));

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

var _CancelButton = _interopRequireDefault(require("../navigation/CancelButton"));

var _DeleteButton = _interopRequireDefault(require("./DeleteButton"));

var _ConfirmRecordDeleteModal = _interopRequireDefault(require("../../../styles/cspace-ui/ConfirmRecordDeleteModal.css"));

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

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 messages = (0, _reactIntl.defineMessages)({
  title: {
    "id": "confirmRecordDeleteModal.title",
    "defaultMessage": "Delete {recordName}"
  },
  prompt: {
    "id": "confirmRecordDeleteModal.prompt",
    "defaultMessage": "Delete {title}?"
  },
  hasRelations: {
    "id": "confirmRecordDeleteModal.hasRelations",
    "defaultMessage": "This record is related to other records. Deleting this record will cause those relationships to be lost."
  },
  hasUses: {
    "id": "confirmRecordDeleteModal.hasUses",
    "defaultMessage": "{title} cannot be deleted because it is used by other records."
  },
  hasRoleUses: {
    "id": "confirmRecordDeleteModal.hasRoleUses",
    "defaultMessage": "{title} cannot be deleted because it is associated with user accounts."
  },
  hasHierarchy: {
    "id": "confirmRecordDeleteModal.hasHierarchy",
    "defaultMessage": "{title} cannot be deleted because it belongs to a hierarchy. To delete this record, first remove its broader and narrower records."
  },
  hasNarrowerHierarchy: {
    "id": "confirmRecordDeleteModal.hasNarrowerHierarchy",
    "defaultMessage": "{title} cannot be deleted because it is a broader record in a hierarchy. To delete this record, first remove its narrower records."
  }
});
const propTypes = {
  config: _propTypes.default.shape({
    allowDeleteHierarchyLeaves: _propTypes.default.bool,
    recordTypes: _propTypes.default.object
  }),
  csid: _propTypes.default.string,
  data: _propTypes.default.instanceOf(_immutable.default.Map),
  isOpen: _propTypes.default.bool,
  isSavePending: _propTypes.default.bool,
  recordType: _propTypes.default.string,

  /* eslint-disable react/no-unused-prop-types */
  // These actually are used, but not detected by eslint.
  checkForRelations: _propTypes.default.func,
  checkForUses: _propTypes.default.func,

  /* eslint-enable react/no-unused-prop-types */
  onCancelButtonClick: _propTypes.default.func,
  onCloseButtonClick: _propTypes.default.func,
  onDeleteButtonClick: _propTypes.default.func
};
const contextTypes = {
  intl: _reactIntl.intlShape
};

class ConfirmRecordDeleteModal extends _react.Component {
  constructor(props) {
    super(props);
    this.renderButtonBar = this.renderButtonBar.bind(this);
    this.state = {};
  }

  componentDidMount() {
    const {
      isOpen
    } = this.props;

    if (isOpen) {
      this.init(this.props);
    }
  } // eslint-disable-next-line camelcase


  UNSAFE_componentWillUpdate(nextProps) {
    const {
      isOpen
    } = this.props;
    const {
      isOpen: nextIsOpen
    } = nextProps;

    if (!isOpen && nextIsOpen) {
      this.init(nextProps);
    }
  }

  canDeleteFromHierarchy() {
    const {
      config,
      csid,
      data
    } = this.props;
    const {
      allowDeleteHierarchyLeaves
    } = config; // If allowDeleteHierarchyLeaves is true, only disallow deleting records that have narrower
    // relations. Otherwise, disallow deleting records that have any (either broader or narrower)
    // hierarchy relations.

    return allowDeleteHierarchyLeaves ? !(0, _recordDataHelpers.hasNarrowerHierarchyRelations)(csid, data) : !(0, _recordDataHelpers.hasHierarchyRelations)(data);
  }

  init(props) {
    // On open check if the record has relations.
    const {
      config,
      recordType,
      checkForRelations,
      checkForUses,
      checkForRoleUses
    } = props;
    const serviceType = (0, _get.default)(config, ['recordTypes', recordType, 'serviceConfig', 'serviceType']);

    if ((serviceType === 'procedure' || serviceType === 'object') && checkForRelations) {
      this.setState({
        hasRelations: undefined,
        hasUses: false
      });
      checkForRelations('affects').then(hasRelations => {
        this.setState({
          hasRelations
        });
      });
    } else if (serviceType === 'authority' && checkForUses) {
      this.setState({
        hasRelations: false,
        hasUses: undefined
      });
      checkForUses().then(hasUses => {
        this.setState({
          hasUses
        });
      });
    } else if (recordType === 'authrole' && checkForRoleUses) {
      this.setState({
        hasRelations: false,
        hasUses: undefined
      });
      checkForRoleUses().then(hasUses => {
        this.setState({
          hasUses
        });
      });
    } else {
      this.setState({
        hasRelations: false,
        hasUses: false
      });
    }
  }

  renderButtonBar() {
    const {
      csid,
      isSavePending,
      onCancelButtonClick,
      onDeleteButtonClick
    } = this.props;
    const {
      hasRelations,
      hasUses
    } = this.state;
    let deleteButton;

    if (!hasUses && this.canDeleteFromHierarchy()) {
      deleteButton = /*#__PURE__*/_react.default.createElement(_DeleteButton.default, {
        csid: csid // Disable the delete button while the check for relations is pending.
        ,
        disabled: typeof hasRelations === 'undefined' // Assume the record is deletable if this modal is being shown.
        ,
        isDeletable: true,
        isSavePending: isSavePending,
        onClick: onDeleteButtonClick
      });
    }

    return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_CancelButton.default, {
      disabled: isSavePending,
      onClick: onCancelButtonClick
    }), deleteButton);
  }

  render() {
    const {
      config,
      data,
      isOpen,
      recordType,
      onCloseButtonClick
    } = this.props;

    if (!isOpen || !data) {
      return null;
    }

    const {
      intl
    } = this.context;
    const {
      hasRelations,
      hasUses
    } = this.state;
    const {
      allowDeleteHierarchyLeaves,
      recordTypes
    } = config;
    const recordTypeConfig = recordTypes[recordType];
    const recordName = intl.formatMessage(recordTypeConfig.messages.record.name);
    const title = recordTypeConfig.title(data, {
      config,
      intl
    });
    let prompt;
    let hasRelationsMessage;
    let hasHierarchyMessage;
    let hasUsesMessage;

    if (typeof hasRelations !== 'undefined' && typeof hasUses !== 'undefined') {
      if (!this.canDeleteFromHierarchy()) {
        hasHierarchyMessage = allowDeleteHierarchyLeaves ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.hasNarrowerHierarchy, {
          values: {
            title
          }
        })) : /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.hasHierarchy, {
          values: {
            title
          }
        }));
      } else if (hasUses) {
        hasUsesMessage = recordType === 'authrole' ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.hasRoleUses, {
          values: {
            title
          }
        })) : /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.hasUses, {
          values: {
            title
          }
        }));
      } else {
        prompt = /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.prompt, {
          values: {
            title
          }
        }));
        hasRelationsMessage = hasRelations ? /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("br", null), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.hasRelations)) : null;
      }
    }

    return /*#__PURE__*/_react.default.createElement(_cspaceLayout.Modal, {
      className: _ConfirmRecordDeleteModal.default.common,
      isOpen: isOpen,
      title: /*#__PURE__*/_react.default.createElement("h1", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.title, {
        values: {
          recordName
        }
      }))),
      closeButtonClassName: "material-icons",
      closeButtonLabel: "close",
      renderButtonBar: this.renderButtonBar,
      onCloseButtonClick: onCloseButtonClick
    }, prompt, hasRelationsMessage, hasHierarchyMessage, hasUsesMessage);
  }

}

exports.default = ConfirmRecordDeleteModal;
ConfirmRecordDeleteModal.propTypes = propTypes;
ConfirmRecordDeleteModal.contextTypes = contextTypes;