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

export function isoDateIsValid(date: string): boolean {
  return ISO_DATE_NO_TIME.test(date);
}

export function isoDateWithoutTimeValidator(): ValidatorFn {
  return (control: AbstractControl): ValidationError => {
    if (control && control.value) {
      const value: string = control.value as string;

      if (!isoDateIsValid(value)) {
        return { invalid: `Ogiltigt datum, vänligen ange YYYY-MM-DD` };
      }
    }

    return null;
  };
}
