"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.buildValidityMessageId = buildValidityMessageId;
exports.getErrorAriaAttributes = getErrorAriaAttributes;
exports.getValidationMessagesIds = getValidationMessagesIds;
exports.getValidityMessages = getValidityMessages;
exports.isPassword = isPassword;
var _get = _interopRequireDefault(require("lodash-es/get"));
var _constants = require("./constants");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
// eslint-disable-next-line you-dont-need-lodash-underscore/get

function isPassword(type) {
  return type === _constants.INPUT_TYPES.PASSWORD;
}
function getValidityMessages({
  validity,
  validationValues
}) {
  const validityType = validity?.type;
  let validityValue;
  if (!!validityType) {
    validityValue = (0, _get.default)(validity, 'value', validationValues[validityType]);
  }

  // If there are no legitimate validity values, then bail.
  if (!validityValue) {
    return [];
  }
  const validityMessages = Array.isArray(validityValue) ? validityValue : [validityValue];
  return validityMessages.filter(message => typeof message === 'string' && !!message.length);
}
function buildValidityMessageId({
  type,
  fieldId,
  position
}) {
  if (!fieldId) {
    return;
  }
  return `${fieldId}-messsage-${type}-${position}`;
}
function getValidationMessagesIds({
  validity,
  validationValues,
  fieldId
}) {
  const validityType = validity?.type;
  if (!fieldId || !validityType) {
    return '';
  }
  const validatedValidityMessages = getValidityMessages({
    validity,
    validationValues
  });
  const ids = validatedValidityMessages.map((_, i) => buildValidityMessageId({
    fieldId,
    type: validityType,
    position: i + 1
  }));
  return ids.join(' ');
}
function getErrorAriaAttributes({
  validity,
  validationValues,
  id
}) {
  const validityType = validity?.type;
  if (!id || !validityType) {
    return '';
  }
  const validationMessagesIds = getValidationMessagesIds({
    validity,
    validationValues,
    fieldId: id
  });
  const isValidationFailed = validityType === _constants.VALIDATION_RULE_TYPES.ERROR;
  const ariaAttrs = {
    ...(validationMessagesIds && {
      'aria-describedby': validationMessagesIds
    }),
    ...(isValidationFailed && {
      'aria-invalid': isValidationFailed
    })
  };
  return ariaAttrs;
}