import { EMAIL_VALIDATION_REGEX } from '../../../constants/validator';
import { InternalFormFieldValidationRule } from './internal-form-field-validation-rule.abstract';
/**
 * This class is a rule that checks if the input is a valid email address
 *
 * @augments {InternalFormFieldValidationRule<string>}
 */
export class EmailFieldRule extends InternalFormFieldValidationRule {
  /**
   * It checks if the input is a valid email address.
   *
   * @param {string} input - string
   * @returns {EvaluateResultTranslation} An object with two properties: isValid and message.
   * @throws {Error} if input is unable to evaluate
   */
  evaluate(input) {
    if (!this.isAcceptedInputType(input)) {
      throw new Error(`Unexpected type of input: ${typeof input}: ${input}`);
    }
    const isValid = EMAIL_VALIDATION_REGEX.test(input.toLowerCase());
    return {
      isValid: isValid,
      message: isValid ? '' : 'Please enter the correct email format.',
    };
  }
  /**
   * If the input is accepted and the status is not disabled and visible, then return true
   *
   * @param {unknown} input - The input to be evaluated.
   * @param {FormFieldStatusMeta} [status] - FormFieldStatusMeta
   * @returns {boolean} A boolean value.
   */
  canEvaluate(input, status) {
    return status
      ? this.isAcceptedInputType(input) && !status.disabled && status.visible
      : this.isAcceptedInputType(input);
  }
  /**
   * If the field is not disabled, visible, and has been touched or modified, then show the error
   *
   * @param {FormFieldStatusMeta} status - FormFieldStatusMeta
   * @returns {boolean} A boolean value.
   */
  shouldShowError(status) {
    return !status.disabled && status.visible && (status.touched || status.modified);
  }
  /**
   * This function returns true if the input is a string with a length greater than zero, otherwise it returns false.
   *
   * @param {unknown} input - The input to be validated.
   * @returns {boolean} A boolean value.
   */
  isAcceptedInputType(input) {
    return typeof input === 'string' && input.length > 0;
  }
}
