import { AbstractControl, ValidatorFn } from '@angular/forms';

export class GemensamPlaneringFormValidator {
  static isGemensamPlaneringValid(obligatoryActivityIds: number[] = []): ValidatorFn {
    return (c: AbstractControl): { [key: string]: string } => {
      let errors: { [key: string]: string } = null;
      const activityIds = (c.get('activityIds')?.value as number[]) || [];
      const obligatoryActivityIdsMissing = !obligatoryActivityIds.every(id => activityIds.includes(id));
      const activityIdsWithoutObligatoryActivityIds = activityIds.filter(
        id => obligatoryActivityIds.indexOf(id) === -1
      );

      if (obligatoryActivityIdsMissing && !activityIdsWithoutObligatoryActivityIds.length) {
        errors = {
          ...errors,
          activityIds: 'Obligatoriska aktiviteter och minst en frivillig aktivitet måste väljas',
        };
      } else {
        if (obligatoryActivityIdsMissing) {
          errors = {
            ...errors,
            activityIds: 'Obligatoriska aktiviteter måste väljas',
          };
        }

        if (!activityIdsWithoutObligatoryActivityIds.length) {
          errors = {
            ...errors,
            activityIds: 'Minst en frivillig aktivitet måste väljas',
          };
        }
      }

      return errors;
    };
  }
}
