import { AbstractControl, ValidatorFn } from '@angular/forms';
import { EMAIL_REGEX } from '@msfa-constants/regex';
import { ValidationError } from '@msfa-models/validation-error.model';

export function emailIsValid(email: string): boolean {
  return EMAIL_REGEX.test(email.toLowerCase());
}

export function EmailValidator(label = 'Fältet'): ValidatorFn {
  return (control: AbstractControl): ValidationError => {
    if (control && control.value) {
      const value: string = control.value as string;

      if (!emailIsValid(value)) {
        return { type: 'invalid', message: `Ogiltig ${label}` };
      }
    }

    return null;
  };
}

export function CommaSeparatedEmailValidator(): ValidatorFn {
  return (control: AbstractControl): ValidationError => {
    if (control && control.value) {
      const values: string[] = (control.value as string)
        .toLowerCase()
        .replaceAll(/\n|\t|\r|\s/g, '')
        .split(',');
      const invalidEmailaddresses = [];

      values.forEach(value => {
        if (value && !EMAIL_REGEX.test(value)) {
          invalidEmailaddresses.push(value);
        }
      });

      if (invalidEmailaddresses.length) {
        const messagePrepend =
          invalidEmailaddresses.length > 1 ? 'Ogiltiga e-postadresser: ' : 'Ogiltig e-postadress: ';
        return { type: 'invalid', message: `${messagePrepend}${invalidEmailaddresses.join(', ')}` };
      }
    }

    return null;
  };
}
