'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 _reactIntl = require('react-intl');

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

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

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

var _CancelButton = require('../navigation/CancelButton');

var _CancelButton2 = _interopRequireDefault(_CancelButton);

var _DeleteButton = require('../record/DeleteButton');

var _DeleteButton2 = _interopRequireDefault(_DeleteButton);

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

var _ConfirmRecordDeleteModal2 = _interopRequireDefault(_ConfirmRecordDeleteModal);

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': '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.'
  },
  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.'
  }
});

var propTypes = {
  config: _propTypes2.default.object,
  csid: _propTypes2.default.string,
  data: _propTypes2.default.instanceOf(_immutable2.default.Map),
  isOpen: _propTypes2.default.bool,
  isSavePending: _propTypes2.default.bool,
  recordType: _propTypes2.default.string,
  checkForRelations: _propTypes2.default.func,
  onCancelButtonClick: _propTypes2.default.func,
  onCloseButtonClick: _propTypes2.default.func,
  onDeleteButtonClick: _propTypes2.default.func
};

var contextTypes = {
  intl: _reactIntl.intlShape
};

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

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

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

    _this.renderButtonBar = _this.renderButtonBar.bind(_this);

    var _this$props = _this.props,
        config = _this$props.config,
        recordType = _this$props.recordType;


    var serviceType = (0, _get2.default)(config, ['recordTypes', recordType, 'serviceConfig', 'serviceType']);

    _this.state = {
      hasRelations: serviceType === 'procedure' || serviceType === 'object' ? undefined : false
    };
    return _this;
  }

  _createClass(ConfirmRecordDeleteModal, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var _this2 = this;

      if (this.props.isOpen && !prevProps.isOpen) {
        // On open check if the record has relations.

        var _props = this.props,
            config = _props.config,
            recordType = _props.recordType,
            checkForRelations = _props.checkForRelations;


        if (checkForRelations) {
          var serviceType = (0, _get2.default)(config, ['recordTypes', recordType, 'serviceConfig', 'serviceType']);

          if (serviceType === 'procedure' || serviceType === 'object') {
            checkForRelations('affects').then(function (hasRelations) {
              _this2.setState({
                hasRelations: hasRelations
              });
            });
          }
        }
      }
    }
  }, {
    key: 'renderButtonBar',
    value: function renderButtonBar() {
      var _props2 = this.props,
          csid = _props2.csid,
          data = _props2.data,
          isSavePending = _props2.isSavePending,
          onCancelButtonClick = _props2.onCancelButtonClick,
          onDeleteButtonClick = _props2.onDeleteButtonClick;
      var hasRelations = this.state.hasRelations;


      var deleteButton = void 0;

      if (!(0, _recordDataHelpers.hasHierarchyRelations)(data)) {
        deleteButton = _react2.default.createElement(_DeleteButton2.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 _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(_CancelButton2.default, {
          disabled: isSavePending,
          onClick: onCancelButtonClick
        }),
        deleteButton
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _props3 = this.props,
          config = _props3.config,
          data = _props3.data,
          isOpen = _props3.isOpen,
          recordType = _props3.recordType,
          onCloseButtonClick = _props3.onCloseButtonClick;


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

      var intl = this.context.intl;
      var hasRelations = this.state.hasRelations;


      var recordTypeConfig = config.recordTypes[recordType];
      var recordName = intl.formatMessage(recordTypeConfig.messages.record.name);
      var title = recordTypeConfig.title(data, { config: config, intl: intl });

      var prompt = void 0;
      var hasRelationsMessage = void 0;
      var hasHierarchyMessage = void 0;

      if ((0, _recordDataHelpers.hasHierarchyRelations)(data)) {
        hasHierarchyMessage = _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.hasHierarchy, { values: { title: title } }));
      } else {
        prompt = _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.prompt, { values: { title: title } }));

        hasRelationsMessage = hasRelations ? _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement('br', null),
          _react2.default.createElement(_reactIntl.FormattedMessage, messages.hasRelations)
        ) : null;
      }

      return _react2.default.createElement(
        _cspaceLayout.Modal,
        {
          className: _ConfirmRecordDeleteModal2.default.common,
          isOpen: isOpen,
          title: _react2.default.createElement(
            'h1',
            null,
            _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.title, { values: { recordName: recordName } }))
          ),
          closeButtonClassName: 'material-icons',
          closeButtonLabel: 'close',
          renderButtonBar: this.renderButtonBar,
          onCloseButtonClick: onCloseButtonClick
        },
        prompt,
        hasRelationsMessage,
        hasHierarchyMessage
      );
    }
  }]);

  return ConfirmRecordDeleteModal;
}(_react.Component);

exports.default = ConfirmRecordDeleteModal;


ConfirmRecordDeleteModal.modalName = 'ConfirmRecordDeleteModal';
ConfirmRecordDeleteModal.propTypes = propTypes;
ConfirmRecordDeleteModal.contextTypes = contextTypes;