// eslint-disable-next-line you-dont-need-lodash-underscore/get
import get from 'lodash-es/get';
import { INPUT_TYPES, VALIDATION_RULE_TYPES } from './constants';
export function isPassword(type) {
  return type === INPUT_TYPES.PASSWORD;
}
export function getValidityMessages({
  validity,
  validationValues
}) {
  const validityType = validity?.type;
  let validityValue;
  if (!!validityType) {
    validityValue = get(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);
}
export function buildValidityMessageId({
  type,
  fieldId,
  position
}) {
  if (!fieldId) {
    return;
  }
  return `${fieldId}-messsage-${type}-${position}`;
}
export 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(' ');
}
export function getErrorAriaAttributes({
  validity,
  validationValues,
  id
}) {
  const validityType = validity?.type;
  if (!id || !validityType) {
    return '';
  }
  const validationMessagesIds = getValidationMessagesIds({
    validity,
    validationValues,
    fieldId: id
  });
  const isValidationFailed = validityType === VALIDATION_RULE_TYPES.ERROR;
  const ariaAttrs = {
    ...(validationMessagesIds && {
      'aria-describedby': validationMessagesIds
    }),
    ...(isValidationFailed && {
      'aria-invalid': isValidationFailed
    })
  };
  return ariaAttrs;
}