'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 _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _get2 = _interopRequireDefault(_get);

var _warning = require('warning');

var _warning2 = _interopRequireDefault(_warning);

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

var _RecordForm = require('../../../styles/cspace-ui/RecordForm.css');

var _RecordForm2 = _interopRequireDefault(_RecordForm);

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 = (0, _get2.default)(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);
    }));
  }

  return component;
}

var propTypes = {
  config: _propTypes3.default.object,
  recordType: _propTypes3.default.string.isRequired,
  vocabulary: _propTypes3.default.string,
  csid: _propTypes3.default.string,
  data: _propTypes3.default.instanceOf(_immutable2.default.Map),
  formName: _propTypes3.default.string,
  readOnly: _propTypes3.default.bool,
  onAddInstance: _propTypes3.default.func,
  onCommit: _propTypes3.default.func,
  onMoveInstance: _propTypes3.default.func,
  onRemoveInstance: _propTypes3.default.func,
  onSortInstances: _propTypes3.default.func
};

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

var childContextTypes = {
  config: _propTypes3.default.object,
  recordData: _propTypes3.default.instanceOf(_immutable2.default.Map),
  recordType: _propTypes3.default.string,
  vocabulary: _propTypes3.default.string,
  csid: _propTypes3.default.string,
  readOnly: _propTypes3.default.bool
};

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

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

    return _possibleConstructorReturn(this, (RecordForm.__proto__ || Object.getPrototypeOf(RecordForm)).apply(this, arguments));
  }

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

      // Get the csid from the data. This may differ from the csid in props, for example if a
      // urn-style csid was entered in the address bar. We always want to supply the guid-style csid
      // in the context.

      var dataCsid = (0, _recordDataHelpers.getCsid)(data);

      return {
        config: config,
        recordType: recordType,
        vocabulary: vocabulary,
        readOnly: readOnly,
        csid: dataCsid || csid,
        recordData: data
      };
    }
  }, {
    key: 'render',
    value: function render() {
      var _props2 = this.props,
          config = _props2.config,
          data = _props2.data,
          formName = _props2.formName,
          readOnly = _props2.readOnly,
          recordType = _props2.recordType,
          onAddInstance = _props2.onAddInstance,
          onCommit = _props2.onCommit,
          onMoveInstance = _props2.onMoveInstance,
          onRemoveInstance = _props2.onRemoveInstance,
          onSortInstances = _props2.onSortInstances;


      var recordTypeConfig = config.recordTypes[recordType];

      if (!recordTypeConfig) {
        return null;
      }

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


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

      var formTemplate = void 0;

      if (formName) {
        formTemplate = (0, _get2.default)(forms, [formName, 'template']);
      }

      if (!formTemplate) {
        // Try to get the configured default form.

        var defaultFormName = recordTypeConfig.defaultForm || 'default';

        if (defaultFormName) {
          formTemplate = (0, _get2.default)(forms, [defaultFormName, 'template']);
        }

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

      if (typeof formTemplate === 'function') {
        var result = formTemplate(data, config);

        if (!result) {
          return null;
        }

        if (typeof result === 'string') {
          // The form template function returned a string. This will be the name of another form
          // template to use.

          formTemplate = (0, _get2.default)(forms, [result, 'template']);

          process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(formTemplate, 'No form template found for computed form name ' + result + ' for form name ' + formName + ' in record type ' + recordType + '. Check the record type plugin configuration.') : void 0;
        } else {
          if ((0, _react.isValidElement)(result)) {
            // The form template function returned a React element to use.

            formTemplate = result;
          }

          process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(formTemplate, 'The computed form template for form name ' + formName + ' in record type ' + recordType + ' did not return a string or a React element. Check the record type plugin configuration.') : void 0;
        }
      }

      var rootPropertyName = Object.keys(fields)[0];

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

      return _react2.default.createElement(
        'div',
        { className: _RecordForm2.default.common },
        formContent
      );
    }
  }]);

  return RecordForm;
}(_react.Component);

exports.default = RecordForm;


RecordForm.propTypes = propTypes;
RecordForm.defaultProps = defaultProps;
RecordForm.childContextTypes = childContextTypes;