'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"); } }; }();

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

const messages = (0, _reactIntl.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}.}}'
  },
  [_errorCodes.ERR_MISSING_REQ_FIELD]: {
    'id': 'validationErrorMessage.ERR_MISSING_REQ_FIELD',
    'defaultMessage': '{fieldName} is required. Please enter a value.'
  },
  [_errorCodes.ERR_UNABLE_TO_VALIDATE]: {
    'id': 'validationErrorMessage.ERR_UNABLE_TO_VALIDATE',
    'defaultMessage': 'An unexpected error occurred while validating this record.'
  },
  default: {
    'id': 'validationErrorMessage.default',
    'defaultMessage': '{fieldName} has an invalid value.'
  }
});

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

const formatErrors = (fieldDescriptor, errors, path = []) => {
  const formattedErrors = [];

  errors.entrySeq().forEach(entry => {
    var _entry = _slicedToArray(entry, 2);

    const key = _entry[0],
          value = _entry[1];


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

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

      const error = value;

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

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

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

  return formattedErrors;
};

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


  if (!errors) {
    return null;
  }

  const formattedErrors = formatErrors(fieldDescriptor, errors);

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

ValidationErrorMessage.propTypes = propTypes;