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

const EMAIL_REGEX = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;

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

      if (!EMAIL_REGEX.test(value.toLowerCase())) {
        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().trim().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;
  };
}
