'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 _propTypes2 = require('prop-types');

var _propTypes3 = _interopRequireDefault(_propTypes2);

var _reactRouter = require('react-router');

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _warning = require('warning');

var _warning2 = _interopRequireDefault(_warning);

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

var _RecordButtonBar2 = _interopRequireDefault(_RecordButtonBar);

var _RecordFormSelector = require('./RecordFormSelector');

var _RecordFormSelector2 = _interopRequireDefault(_RecordFormSelector);

var _RecordHistory = require('./RecordHistory');

var _RecordHistory2 = _interopRequireDefault(_RecordHistory);

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

var _ConfirmRecordNavigationModal2 = _interopRequireDefault(_ConfirmRecordNavigationModal);

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

var _ConfirmRecordDeleteModal2 = _interopRequireDefault(_ConfirmRecordDeleteModal);

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

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; }

function renderTemplate(component, messages, handlers) {
  var overrideProps = {};
  var type = component.type;

  if (type) {
    var _propTypes = type.propTypes;

    if (_propTypes) {
      Object.keys(handlers).forEach(function (handlerName) {
        if (_propTypes[handlerName] && !component.props[handlerName]) {
          overrideProps[handlerName] = handlers[handlerName];
        }
      });
    }
  }

  return _react2.default.cloneElement(component, overrideProps, _react2.default.Children.map(component.props.children, function (child) {
    return renderTemplate(child, messages, handlers);
  }));
}

var propTypes = {
  config: _propTypes3.default.object,
  recordType: _propTypes3.default.string.isRequired,
  vocabulary: _propTypes3.default.string,
  csid: _propTypes3.default.string,
  cloneCsid: _propTypes3.default.string,
  data: _propTypes3.default.instanceOf(_immutable2.default.Map),
  formName: _propTypes3.default.string,
  validationErrors: _propTypes3.default.instanceOf(_immutable2.default.Map),
  isModified: _propTypes3.default.bool,
  isSavePending: _propTypes3.default.bool,
  openModalName: _propTypes3.default.string,
  createNewRecord: _propTypes3.default.func,
  readRecord: _propTypes3.default.func,
  onAddInstance: _propTypes3.default.func,
  onCommit: _propTypes3.default.func,
  onMoveInstance: _propTypes3.default.func,
  onRemoveInstance: _propTypes3.default.func,
  onRecordCreated: _propTypes3.default.func,
  onSaveCancelled: _propTypes3.default.func,
  closeModal: _propTypes3.default.func,
  openModal: _propTypes3.default.func,
  save: _propTypes3.default.func,
  revert: _propTypes3.default.func,
  clone: _propTypes3.default.func,
  transitionRecord: _propTypes3.default.func,
  removeValidationNotification: _propTypes3.default.func,
  setForm: _propTypes3.default.func,
  validateRecordData: _propTypes3.default.func,
  onRecordTransitioned: _propTypes3.default.func
};

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

var childContextTypes = {
  config: _propTypes3.default.object,
  recordType: _propTypes3.default.string,
  vocabulary: _propTypes3.default.string,
  csid: _propTypes3.default.string
};

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

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

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

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

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

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

    _this.handleModalCancelButtonClick = _this.handleModalCancelButtonClick.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);
    return _this;
  }

  _createClass(RecordEditor, [{
    key: 'getChildContext',
    value: function getChildContext() {
      var _props = this.props,
          config = _props.config,
          csid = _props.csid,
          recordType = _props.recordType,
          vocabulary = _props.vocabulary;


      return {
        config: config,
        csid: csid,
        recordType: recordType,
        vocabulary: vocabulary
      };
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.initRecord();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var _props2 = this.props,
          recordType = _props2.recordType,
          vocabulary = _props2.vocabulary,
          csid = _props2.csid,
          cloneCsid = _props2.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 removeValidationNotification = this.props.removeValidationNotification;


      if (removeValidationNotification) {
        removeValidationNotification();
      }
    }
  }, {
    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: 'handleModalCancelButtonClick',
    value: function handleModalCancelButtonClick() {
      var _props4 = this.props,
          closeModal = _props4.closeModal,
          onSaveCancelled = _props4.onSaveCancelled;


      if (closeModal) {
        closeModal(false);
      }

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


      var transitionName = 'delete';

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

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


      if (save) {
        // 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;

        save(callback);
      }

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


      if (revert) {
        revert();
      }

      if (closeModal) {
        closeModal(true);
      }
    }
  }, {
    key: 'handleCloneButtonClick',
    value: function handleCloneButtonClick() {
      var _props8 = this.props,
          clone = _props8.clone,
          csid = _props8.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 _props9 = this.props,
          save = _props9.save,
          onRecordCreated = _props9.onRecordCreated;


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


      if (validateRecordData) {
        validateRecordData();
      }
    }
  }, {
    key: 'handleRecordFormSelectorCommit',
    value: function handleRecordFormSelectorCommit(path, value) {
      var setForm = this.props.setForm;


      if (setForm) {
        setForm(value);
      }
    }
  }, {
    key: 'renderConfirmNavigationModal',
    value: function renderConfirmNavigationModal() {
      var _props10 = this.props,
          isModified = _props10.isModified,
          isSavePending = _props10.isSavePending,
          openModalName = _props10.openModalName,
          validationErrors = _props10.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 _props11 = this.props,
          csid = _props11.csid,
          isSavePending = _props11.isSavePending,
          openModalName = _props11.openModalName;


      return _react2.default.createElement(_ConfirmRecordDeleteModal2.default, {
        csid: csid,
        isOpen: openModalName === _ConfirmRecordDeleteModal2.default.modalName,
        isSavePending: isSavePending,
        onCancelButtonClick: this.handleModalCancelButtonClick,
        onCloseButtonClick: this.handleModalCancelButtonClick,
        onDeleteButtonClick: this.handleConfirmDeleteButtonClick
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props12 = this.props,
          config = _props12.config,
          csid = _props12.csid,
          data = _props12.data,
          formName = _props12.formName,
          isModified = _props12.isModified,
          isSavePending = _props12.isSavePending,
          recordType = _props12.recordType,
          validationErrors = _props12.validationErrors,
          onAddInstance = _props12.onAddInstance,
          onCommit = _props12.onCommit,
          onMoveInstance = _props12.onMoveInstance,
          onRemoveInstance = _props12.onRemoveInstance;


      var recordTypeConfig = config.recordTypes[recordType];

      if (!recordTypeConfig) {
        return null;
      }

      var forms = recordTypeConfig.forms,
          messages = recordTypeConfig.messages;


      var handlers = {
        onAddInstance: onAddInstance,
        onCommit: onCommit,
        onMoveInstance: onMoveInstance,
        onRemoveInstance: onRemoveInstance
      };

      var formTemplate = forms[formName].template;

      process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(formTemplate, 'No form template found for form name ' + formName + ' in record type ' + recordType + '. Check the record type plugin configuration.') : void 0;

      var formContent = _react2.default.cloneElement(formTemplate, {
        name: _recordDataHelpers.DOCUMENT_PROPERTY_NAME,
        value: data.get(_recordDataHelpers.DOCUMENT_PROPERTY_NAME),
        children: _react2.default.Children.map(formTemplate.props.children, function (child) {
          return renderTemplate(child, messages, handlers);
        })
      });

      return _react2.default.createElement(
        'form',
        {
          autoComplete: 'off',
          className: _RecordEditor2.default.common
        },
        _react2.default.createElement(
          'header',
          null,
          _react2.default.createElement(_RecordButtonBar2.default, {
            csid: csid,
            isModified: isModified,
            isSavePending: isSavePending,
            validationErrors: validationErrors,
            onSaveButtonClick: this.handleSaveButtonClick,
            onSaveButtonErrorBadgeClick: this.handleSaveButtonErrorBadgeClick,
            onRevertButtonClick: this.handleRevertButtonClick,
            onCloneButtonClick: this.handleCloneButtonClick,
            onDeleteButtonClick: this.handleDeleteButtonClick
          }),
          _react2.default.createElement(_RecordFormSelector2.default, {
            config: config,
            formName: formName,
            recordType: recordType,
            onCommit: this.handleRecordFormSelectorCommit
          }),
          _react2.default.createElement(_RecordHistory2.default, {
            data: data,
            isModified: isModified,
            isSavePending: isSavePending
          })
        ),
        formContent,
        _react2.default.createElement(
          'footer',
          null,
          _react2.default.createElement(_RecordButtonBar2.default, {
            csid: csid,
            isModified: isModified,
            isSavePending: isSavePending,
            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()
      );
    }
  }]);

  return RecordEditor;
}(_react.Component);

exports.default = RecordEditor;


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