'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

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 _reactRouter = require('react-router');

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _get2 = _interopRequireDefault(_get);

var _RecordButtonBar = require('./RecordButtonBar');

var _RecordButtonBar2 = _interopRequireDefault(_RecordButtonBar);

var _RecordHeader = require('./RecordHeader');

var _RecordHeader2 = _interopRequireDefault(_RecordHeader);

var _ConfirmRecordNavigationModal = require('./ConfirmRecordNavigationModal');

var _ConfirmRecordNavigationModal2 = _interopRequireDefault(_ConfirmRecordNavigationModal);

var _ConfirmRecordDeleteModal = require('./ConfirmRecordDeleteModal');

var _ConfirmRecordDeleteModal2 = _interopRequireDefault(_ConfirmRecordDeleteModal);

var _LockRecordModal = require('./LockRecordModal');

var _LockRecordModal2 = _interopRequireDefault(_LockRecordModal);

var _HierarchyReparentNotifier = require('./HierarchyReparentNotifier');

var _HierarchyReparentNotifier2 = _interopRequireDefault(_HierarchyReparentNotifier);

var _RecordFormContainer = require('../../containers/record/RecordFormContainer');

var _RecordFormContainer2 = _interopRequireDefault(_RecordFormContainer);

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

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

var _workflowStateHelpers = require('../../helpers/workflowStateHelpers');

var _RecordEditor = require('../../../styles/cspace-ui/RecordEditor.css');

var _RecordEditor2 = _interopRequireDefault(_RecordEditor);

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 propTypes = {
  config: _propTypes2.default.object,
  recordType: _propTypes2.default.string.isRequired,
  vocabulary: _propTypes2.default.string,
  csid: _propTypes2.default.string,
  cloneCsid: _propTypes2.default.string,
  data: _propTypes2.default.instanceOf(_immutable2.default.Map),
  dockTop: _propTypes2.default.number,
  formName: _propTypes2.default.string,
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  validationErrors: _propTypes2.default.instanceOf(_immutable2.default.Map),
  vocabularyWorkflowState: _propTypes2.default.string,
  isModified: _propTypes2.default.bool,
  isReadPending: _propTypes2.default.bool,
  isSavePending: _propTypes2.default.bool,
  isHardDelete: _propTypes2.default.bool,
  // The workflow state of the related subject (aka primary) record when we're in a secondary tab.
  relatedSubjectWorkflowState: _propTypes2.default.string,
  openModalName: _propTypes2.default.string,
  checkForRelations: _propTypes2.default.func,
  createNewRecord: _propTypes2.default.func,
  readRecord: _propTypes2.default.func,
  onRecordCreated: _propTypes2.default.func,
  onSaveCancelled: _propTypes2.default.func,
  closeModal: _propTypes2.default.func,
  openModal: _propTypes2.default.func,
  deleteRecord: _propTypes2.default.func,
  save: _propTypes2.default.func,
  saveWithTransition: _propTypes2.default.func,
  revert: _propTypes2.default.func,
  clone: _propTypes2.default.func,
  transitionRecord: _propTypes2.default.func,
  removeNotification: _propTypes2.default.func,
  removeValidationNotification: _propTypes2.default.func,
  setForm: _propTypes2.default.func,
  validateRecordData: _propTypes2.default.func,
  onRecordDeleted: _propTypes2.default.func,
  onRecordTransitioned: _propTypes2.default.func
};

var defaultProps = {
  data: _immutable2.default.Map()
};

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

  function RecordEditor() {
    _classCallCheck(this, RecordEditor);

    // Confirm delete modal button handlers.

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

    _this.handleConfirmDeleteButtonClick = _this.handleConfirmDeleteButtonClick.bind(_this);

    // Confirm navigation modal button handlers.

    _this.handleConfirmNavigationSaveButtonClick = _this.handleConfirmNavigationSaveButtonClick.bind(_this);

    _this.handleConfirmNavigationRevertButtonClick = _this.handleConfirmNavigationRevertButtonClick.bind(_this);

    // Lock modal button handlers.

    _this.handleSaveOnlyButtonClick = _this.handleSaveOnlyButtonClick.bind(_this);
    _this.handleSaveLockButtonClick = _this.handleSaveLockButtonClick.bind(_this);

    // Shared modal handlers.

    _this.handleModalCancelButtonClick = _this.handleModalCancelButtonClick.bind(_this);

    // Button bar handlers.

    _this.handleDeprecateButtonClick = _this.handleDeprecateButtonClick.bind(_this);
    _this.handleSaveButtonClick = _this.handleSaveButtonClick.bind(_this);
    _this.handleSaveButtonErrorBadgeClick = _this.handleSaveButtonErrorBadgeClick.bind(_this);
    _this.handleRevertButtonClick = _this.handleRevertButtonClick.bind(_this);
    _this.handleCloneButtonClick = _this.handleCloneButtonClick.bind(_this);
    _this.handleDeleteButtonClick = _this.handleDeleteButtonClick.bind(_this);
    _this.handleRecordFormSelectorCommit = _this.handleRecordFormSelectorCommit.bind(_this);
    _this.handleUndeprecateButtonClick = _this.handleUndeprecateButtonClick.bind(_this);
    return _this;
  }

  _createClass(RecordEditor, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.initRecord();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var _props = this.props,
          recordType = _props.recordType,
          vocabulary = _props.vocabulary,
          csid = _props.csid,
          cloneCsid = _props.cloneCsid;
      var prevRecordType = prevProps.recordType,
          prevVocabulary = prevProps.vocabulary,
          prevCsid = prevProps.csid,
          prevCloneCsid = prevProps.cloneCsid;


      if (recordType !== prevRecordType || vocabulary !== prevVocabulary || csid !== prevCsid || cloneCsid !== prevCloneCsid) {
        this.initRecord();
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      var _props2 = this.props,
          removeNotification = _props2.removeNotification,
          removeValidationNotification = _props2.removeValidationNotification;


      if (removeValidationNotification) {
        removeValidationNotification();
      }

      if (removeNotification) {
        removeNotification(_HierarchyReparentNotifier2.default.notificationID);
      }
    }
  }, {
    key: 'initRecord',
    value: function initRecord() {
      var _props3 = this.props,
          csid = _props3.csid,
          cloneCsid = _props3.cloneCsid,
          createNewRecord = _props3.createNewRecord,
          readRecord = _props3.readRecord,
          removeValidationNotification = _props3.removeValidationNotification;


      if (removeValidationNotification) {
        removeValidationNotification();
      }

      if (csid) {
        if (readRecord) {
          readRecord();
        }
      } else if (createNewRecord) {
        createNewRecord(cloneCsid);
      }
    }
  }, {
    key: 'save',
    value: function save(onRecordCreated) {
      var _props4 = this.props,
          config = _props4.config,
          recordType = _props4.recordType,
          openModal = _props4.openModal,
          save = _props4.save,
          saveWithTransition = _props4.saveWithTransition;


      var recordTypeConfig = config.recordTypes[recordType];
      var lockOnSave = recordTypeConfig.lockOnSave;


      if (lockOnSave === 'prompt' && openModal) {
        openModal(_LockRecordModal2.default.modalName);

        return false;
      }

      if (lockOnSave === true && saveWithTransition) {
        saveWithTransition('lock', onRecordCreated);
      } else if (save) {
        save(onRecordCreated);
      }

      return true;
    }
  }, {
    key: 'handleModalCancelButtonClick',
    value: function handleModalCancelButtonClick() {
      var _props5 = this.props,
          closeModal = _props5.closeModal,
          onSaveCancelled = _props5.onSaveCancelled;


      if (closeModal) {
        closeModal(false);
      }

      if (onSaveCancelled) {
        onSaveCancelled();
      }
    }
  }, {
    key: 'handleUndeprecateButtonClick',
    value: function handleUndeprecateButtonClick() {
      var _props6 = this.props,
          transitionRecord = _props6.transitionRecord,
          onRecordTransitioned = _props6.onRecordTransitioned;


      var transitionName = 'undeprecate';

      if (transitionRecord) {
        transitionRecord(transitionName).then(function () {
          if (onRecordTransitioned) {
            onRecordTransitioned(transitionName);
          }
        });
      }
    }
  }, {
    key: 'handleDeprecateButtonClick',
    value: function handleDeprecateButtonClick() {
      var _props7 = this.props,
          transitionRecord = _props7.transitionRecord,
          onRecordTransitioned = _props7.onRecordTransitioned;


      var transitionName = 'deprecate';

      if (transitionRecord) {
        transitionRecord(transitionName).then(function () {
          if (onRecordTransitioned) {
            onRecordTransitioned(transitionName);
          }
        });
      }
    }
  }, {
    key: 'handleConfirmDeleteButtonClick',
    value: function handleConfirmDeleteButtonClick() {
      var _props8 = this.props,
          closeModal = _props8.closeModal,
          isHardDelete = _props8.isHardDelete,
          deleteRecord = _props8.deleteRecord,
          onRecordDeleted = _props8.onRecordDeleted,
          transitionRecord = _props8.transitionRecord,
          onRecordTransitioned = _props8.onRecordTransitioned;


      if (isHardDelete) {
        if (deleteRecord) {
          deleteRecord().then(function () {
            if (closeModal) {
              closeModal(true);
            }

            if (onRecordDeleted) {
              onRecordDeleted();
            }
          });
        }
      } else {
        var transitionName = 'delete';

        if (transitionRecord) {
          transitionRecord(transitionName).then(function () {
            if (closeModal) {
              closeModal(true);
            }

            if (onRecordTransitioned) {
              onRecordTransitioned(transitionName);
            }
          });
        }
      }
    }
  }, {
    key: 'handleConfirmNavigationSaveButtonClick',
    value: function handleConfirmNavigationSaveButtonClick() {
      var _props9 = this.props,
          closeModal = _props9.closeModal,
          onRecordCreated = _props9.onRecordCreated;

      // Wrap the onRecordCreated callback in a function that sets isNavigating to true. This lets
      // the callback know that we're already navigating away, so it should not do any navigation
      // of its own.

      var callback = onRecordCreated ? function (newRecordCsid) {
        onRecordCreated(newRecordCsid, true);
      } : undefined;

      var saveCalled = this.save(callback);

      if (saveCalled && closeModal) {
        closeModal(true);
      }
    }
  }, {
    key: 'handleConfirmNavigationRevertButtonClick',
    value: function handleConfirmNavigationRevertButtonClick() {
      var _props10 = this.props,
          closeModal = _props10.closeModal,
          revert = _props10.revert;


      if (revert) {
        revert();
      }

      if (closeModal) {
        closeModal(true);
      }
    }
  }, {
    key: 'handleCloneButtonClick',
    value: function handleCloneButtonClick() {
      var _props11 = this.props,
          clone = _props11.clone,
          csid = _props11.csid;


      if (clone) {
        clone(csid);
      }
    }
  }, {
    key: 'handleDeleteButtonClick',
    value: function handleDeleteButtonClick() {
      var openModal = this.props.openModal;


      if (openModal) {
        openModal(_ConfirmRecordDeleteModal2.default.modalName);
      }
    }
  }, {
    key: 'handleRevertButtonClick',
    value: function handleRevertButtonClick() {
      var revert = this.props.revert;


      if (revert) {
        revert();
      }
    }
  }, {
    key: 'handleSaveButtonClick',
    value: function handleSaveButtonClick() {
      var onRecordCreated = this.props.onRecordCreated;


      this.save(onRecordCreated);
    }
  }, {
    key: 'handleSaveButtonErrorBadgeClick',
    value: function handleSaveButtonErrorBadgeClick() {
      var validateRecordData = this.props.validateRecordData;


      if (validateRecordData) {
        validateRecordData();
      }
    }
  }, {
    key: 'handleSaveOnlyButtonClick',
    value: function handleSaveOnlyButtonClick() {
      var _props12 = this.props,
          save = _props12.save,
          closeModal = _props12.closeModal,
          onRecordCreated = _props12.onRecordCreated;


      if (save) {
        save(onRecordCreated).then(function () {
          if (closeModal) {
            closeModal(true);
          }
        });
      }
    }
  }, {
    key: 'handleSaveLockButtonClick',
    value: function handleSaveLockButtonClick() {
      var _props13 = this.props,
          saveWithTransition = _props13.saveWithTransition,
          closeModal = _props13.closeModal,
          onRecordCreated = _props13.onRecordCreated;


      if (saveWithTransition) {
        saveWithTransition('lock', onRecordCreated).then(function () {
          if (closeModal) {
            closeModal(true);
          }
        });
      }
    }
  }, {
    key: 'handleRecordFormSelectorCommit',
    value: function handleRecordFormSelectorCommit(path, value) {
      var setForm = this.props.setForm;


      if (setForm) {
        setForm(value);
      }
    }
  }, {
    key: 'renderConfirmNavigationModal',
    value: function renderConfirmNavigationModal() {
      var _props14 = this.props,
          isModified = _props14.isModified,
          isSavePending = _props14.isSavePending,
          openModalName = _props14.openModalName,
          validationErrors = _props14.validationErrors;


      return _react2.default.createElement(_ConfirmRecordNavigationModal2.default, {
        isOpen: openModalName === _ConfirmRecordNavigationModal2.default.modalName,
        isModified: isModified,
        isSavePending: isSavePending,
        validationErrors: validationErrors,
        onCancelButtonClick: this.handleModalCancelButtonClick,
        onCloseButtonClick: this.handleModalCancelButtonClick,
        onSaveButtonClick: this.handleConfirmNavigationSaveButtonClick,
        onSaveButtonErrorBadgeClick: this.handleSaveButtonErrorBadgeClick,
        onRevertButtonClick: this.handleConfirmNavigationRevertButtonClick
      });
    }
  }, {
    key: 'renderConfirmRecordDeleteModal',
    value: function renderConfirmRecordDeleteModal() {
      var _props15 = this.props,
          config = _props15.config,
          csid = _props15.csid,
          data = _props15.data,
          isSavePending = _props15.isSavePending,
          openModalName = _props15.openModalName,
          recordType = _props15.recordType,
          checkForRelations = _props15.checkForRelations;


      return _react2.default.createElement(_ConfirmRecordDeleteModal2.default, {
        config: config,
        csid: csid,
        data: data,
        isOpen: openModalName === _ConfirmRecordDeleteModal2.default.modalName,
        isSavePending: isSavePending,
        recordType: recordType,
        checkForRelations: checkForRelations,
        onCancelButtonClick: this.handleModalCancelButtonClick,
        onCloseButtonClick: this.handleModalCancelButtonClick,
        onDeleteButtonClick: this.handleConfirmDeleteButtonClick
      });
    }
  }, {
    key: 'renderLockRecordModal',
    value: function renderLockRecordModal() {
      var _props16 = this.props,
          config = _props16.config,
          csid = _props16.csid,
          isSavePending = _props16.isSavePending,
          openModalName = _props16.openModalName,
          recordType = _props16.recordType;


      var recordTypeConfig = config.recordTypes[recordType];
      var lockOnSave = recordTypeConfig.lockOnSave;


      if (lockOnSave !== 'prompt') {
        return null;
      }

      return _react2.default.createElement(_LockRecordModal2.default, {
        csid: csid,
        isOpen: openModalName === _LockRecordModal2.default.modalName,
        isSavePending: isSavePending,
        onCancelButtonClick: this.handleModalCancelButtonClick,
        onCloseButtonClick: this.handleModalCancelButtonClick,
        onSaveOnlyButtonClick: this.handleSaveOnlyButtonClick,
        onSaveLockButtonClick: this.handleSaveLockButtonClick
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props17 = this.props,
          config = _props17.config,
          csid = _props17.csid,
          data = _props17.data,
          dockTop = _props17.dockTop,
          formName = _props17.formName,
          isModified = _props17.isModified,
          isReadPending = _props17.isReadPending,
          isSavePending = _props17.isSavePending,
          perms = _props17.perms,
          recordType = _props17.recordType,
          relatedSubjectWorkflowState = _props17.relatedSubjectWorkflowState,
          validationErrors = _props17.validationErrors,
          vocabulary = _props17.vocabulary,
          vocabularyWorkflowState = _props17.vocabularyWorkflowState;


      var recordTypeConfig = config.recordTypes[recordType];

      if (!recordTypeConfig) {
        return null;
      }

      var selectedFormName = formName || recordTypeConfig.defaultForm || 'default';
      var relatedSubjectLocked = (0, _workflowStateHelpers.isLocked)(relatedSubjectWorkflowState);
      var vocabularyLocked = (0, _workflowStateHelpers.isLocked)(vocabularyWorkflowState);
      var immutable = (0, _recordDataHelpers.isRecordImmutable)(data);

      var readOnly = isReadPending || immutable || !(csid ? (0, _permissionHelpers.canUpdate)(recordType, perms) : (0, _permissionHelpers.canCreate)(recordType, perms));

      var isCloneable =
      // The record must be saved.
      !!csid && !vocabularyLocked &&
      // If we're editing an object record in a secondary tab, and the primary record is locked,
      // a new cloned record would not be able to be related to the primary, so the clone
      // button should not appear.
      !relatedSubjectLocked &&
      // We must have permission to create a new record of the type.
      (0, _permissionHelpers.canCreate)(recordType, perms);

      var isDeletable = !!csid && !immutable && !vocabularyLocked && (
      // Security resources don't have soft-delete, so also need to check hard delete.
      (0, _permissionHelpers.canSoftDelete)(recordType, perms) || (0, _permissionHelpers.canDelete)(recordType, perms));

      var serviceType = (0, _get2.default)(recordTypeConfig, ['serviceConfig', 'serviceType']);
      var showDeprecationButtons = config.termDeprecationEnabled && serviceType === 'authority';
      var isDeprecated = (0, _recordDataHelpers.isRecordDeprecated)(data);

      return _react2.default.createElement(
        'form',
        { className: _RecordEditor2.default.common, autoComplete: 'off' },
        _react2.default.createElement(_RecordHeader2.default, {
          config: config,
          data: data,
          dockTop: dockTop,
          formName: selectedFormName,
          isCloneable: isCloneable,
          isDeletable: isDeletable,
          isDeprecated: isDeprecated,
          isModified: isModified,
          isReadPending: isReadPending,
          isSavePending: isSavePending,
          readOnly: readOnly,
          recordType: recordType,
          showDeprecationButtons: showDeprecationButtons,
          validationErrors: validationErrors,
          onCloneButtonClick: this.handleCloneButtonClick,
          onCommit: this.handleRecordFormSelectorCommit,
          onDeprecateButtonClick: this.handleDeprecateButtonClick,
          onDeleteButtonClick: this.handleDeleteButtonClick,
          onSaveButtonClick: this.handleSaveButtonClick,
          onSaveButtonErrorBadgeClick: this.handleSaveButtonErrorBadgeClick,
          onRevertButtonClick: this.handleRevertButtonClick,
          onUndeprecateButtonClick: this.handleUndeprecateButtonClick
        }),
        _react2.default.createElement(_RecordFormContainer2.default, {
          config: config,
          csid: csid,
          data: data,
          formName: selectedFormName,
          readOnly: readOnly,
          recordType: recordType,
          vocabulary: vocabulary
        }),
        _react2.default.createElement(
          'footer',
          null,
          _react2.default.createElement(_RecordButtonBar2.default, {
            isCloneable: isCloneable,
            isDeletable: isDeletable,
            isDeprecated: isDeprecated,
            isModified: isModified,
            isReadPending: isReadPending,
            isSavePending: isSavePending,
            readOnly: readOnly,
            showDeprecationButtons: showDeprecationButtons,
            validationErrors: validationErrors,
            onSaveButtonClick: this.handleSaveButtonClick,
            onSaveButtonErrorBadgeClick: this.handleSaveButtonErrorBadgeClick,
            onRevertButtonClick: this.handleRevertButtonClick,
            onCloneButtonClick: this.handleCloneButtonClick,
            onDeleteButtonClick: this.handleDeleteButtonClick
          })
        ),
        _react2.default.createElement(_reactRouter.Prompt, {
          when: isModified && !isSavePending,
          message: _ConfirmRecordNavigationModal2.default.modalName
        }),
        this.renderConfirmNavigationModal(),
        this.renderConfirmRecordDeleteModal(),
        this.renderLockRecordModal()
      );
    }
  }]);

  return RecordEditor;
}(_react.Component);

exports.default = RecordEditor;


RecordEditor.propTypes = propTypes;
RecordEditor.defaultProps = defaultProps;