'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 _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _defineMessages;

exports.default = ValidationErrorMessage;

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 _recordDataHelpers = require('../../helpers/recordDataHelpers');

var _configHelpers = require('../../helpers/configHelpers');

var _errorCodes = require('../../constants/errorCodes');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var messages = (0, _reactIntl.defineMessages)((_defineMessages = {}, _defineProperty(_defineMessages, _errorCodes.ERR_DATA_TYPE, {
  'id': 'validationErrorMessage.ERR_DATA_TYPE',
  'defaultMessage': '{dataType, select, DATA_TYPE_INT {{fieldName} must be an integer. Correct the value {value}.} DATA_TYPE_FLOAT {{fieldName} must be a number. Correct the value {value}.} DATA_TYPE_DATE {{fieldName} must be a date in the format YYYY-MM-DD. Correct the value {value}.} other {{fieldName} has an invalid value for the data type {dataType}. Correct the value {value}.}}'
}), _defineProperty(_defineMessages, _errorCodes.ERR_MISSING_REQ_FIELD, {
  'id': 'validationErrorMessage.ERR_MISSING_REQ_FIELD',
  'defaultMessage': '{fieldName} is required. Please enter a value.'
}), _defineProperty(_defineMessages, _errorCodes.ERR_UNABLE_TO_VALIDATE, {
  'id': 'validationErrorMessage.ERR_UNABLE_TO_VALIDATE',
  'defaultMessage': 'An unexpected error occurred while validating this record.'
}), _defineProperty(_defineMessages, 'default', {
  'id': 'validationErrorMessage.default',
  'defaultMessage': '{fieldName} has an invalid value.'
}), _defineMessages));

var propTypes = {
  errors: _propTypes2.default.instanceOf(_immutable2.default.Map),
  fieldDescriptor: _propTypes2.default.object
};

var formatErrors = function formatErrors(fieldDescriptor, errors) {
  var path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];

  var formattedErrors = [];

  errors.entrySeq().forEach(function (entry) {
    var _entry = _slicedToArray(entry, 2),
        key = _entry[0],
        value = _entry[1];

    if (key === _recordDataHelpers.ERROR_KEY) {
      var id = path.join('.');
      var fieldDescriptorPath = (0, _configHelpers.dataPathToFieldDescriptorPath)(path);
      var fieldMessages = (0, _get2.default)(fieldDescriptor, [].concat(_toConsumableArray(fieldDescriptorPath), [_configHelpers.configKey, 'messages']));
      var fieldNameMessage = (0, _get2.default)(fieldMessages, 'fullName') || (0, _get2.default)(fieldMessages, 'name');

      var fieldName = fieldNameMessage ? _react2.default.createElement(_reactIntl.FormattedMessage, fieldNameMessage) : path[path.length - 1];

      var error = value;

      if (error) {
        var errorMessage = error.get('message') || messages[error.get('code')] || messages.default;
        var values = error.set('fieldName', fieldName).toJS();

        var formattedMessage = _react2.default.createElement(
          'li',
          { key: id },
          _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, errorMessage, { values: values }))
        );

        formattedErrors.push(formattedMessage);
      }
    } else if (value) {
      formattedErrors.push.apply(formattedErrors, _toConsumableArray(formatErrors(fieldDescriptor, value, [].concat(_toConsumableArray(path), [key]))));
    }
  });

  return formattedErrors;
};

function ValidationErrorMessage(props) {
  var errors = props.errors,
      fieldDescriptor = props.fieldDescriptor;


  if (!errors) {
    return null;
  }

  var formattedErrors = formatErrors(fieldDescriptor, errors);

  return _react2.default.createElement(
    'ul',
    null,
    formattedErrors
  );
}

ValidationErrorMessage.propTypes = propTypes;