function domainValidator(dataSet) {
  dataSet.forEach(function (eachRecord) {
    return eachRecord.getField('key').checkValidity();
  });
}

function handleUpdate(_ref) {
  var value = _ref.value,
      name = _ref.name,
      record = _ref.record,
      dataSet = _ref.dataSet;

  if (name === 'key') {
    domainValidator(dataSet);
  }
}

function handleRemove(_ref2) {
  var dataSet = _ref2.dataSet;
  domainValidator(dataSet);
}

export default (function (_ref3) {
  var formatMessage = _ref3.formatMessage;

  function checkKey(value, name, record) {
    var pa = /^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/)?([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$/;

    if (value) {
      if (!pa.test(value)) {
        return formatMessage({
          id: 'domain.annotation.check.failed'
        });
      }

      var ds = record.dataSet;
      var hasRepeat = ds.some(function (annotationRecord) {
        return annotationRecord.id !== record.id && value === annotationRecord.get('key');
      });

      if (hasRepeat) {
        return formatMessage({
          id: 'domain.annotation.check.repeat'
        });
      }
    }
  }

  function checkValue(value, name, record) {
    if (!value && record.get('key')) {
      return formatMessage({
        id: 'mapping.keyValueSpan'
      });
    }
  }

  return {
    autoCreate: true,
    autoQuery: false,
    selection: false,
    paging: false,
    fields: [{
      name: 'key',
      type: 'string',
      validator: checkKey,
      maxLength: 316,
      label: formatMessage({
        id: 'key'
      })
    }, {
      name: 'value',
      type: 'string',
      validator: checkValue,
      label: formatMessage({
        id: 'value'
      })
    }],
    events: {
      update: handleUpdate,
      remove: handleRemove
    }
  };
});