import { AbstractControl, ValidatorFn } from '@angular/forms';
import { RoleEnum } from '@msfa-enums/role.enum';
import { TreeNode } from '@msfa-shared/components/tree-nodes-selector/services/tree-nodes-selector.service';
import { emailIsValid } from './email.validator';

export class EmployeeValidator {
  static isEmployeeValid(hasSelectedUtforandeVerksamhetFn: (treeNode: TreeNode) => boolean): ValidatorFn {
    return (c: AbstractControl): { [key: string]: string } => {
      let errors: { [key: string]: string } = null;
      const email = c.get('email')?.value as string;
      const roles = c.get('roles')?.value as { [key: string]: boolean };
      const tjanster = c.get('tjanster')?.value as string;
      const allaUtforandeVerksamheter = c.get('allaUtforandeVerksamheter')?.value as boolean;
      const utforandeVerksamheter = c.get('utforandeVerksamheter').value as TreeNode;
      const rolesWithObligatoryFormElements = Object.entries(roles)
        .filter(([key, value]) => !!(value && key !== RoleEnum.MSFA_AuthAdmin))
        .map(([key]) => key);

      if (!email) {
        errors = {
          ...errors,
          email: 'E-postadress är obligatoriskt',
        };
      }
      if (email && !emailIsValid(email)) {
        errors = {
          ...errors,
          email: 'Ogiltig e-postadress',
        };
      }

      if (rolesWithObligatoryFormElements.length) {
        if (!tjanster) {
          errors = {
            ...errors,
            tjanster: 'Minst en tjänst behöver väljas',
          };
        }
        if (!allaUtforandeVerksamheter && !hasSelectedUtforandeVerksamhetFn(utforandeVerksamheter)) {
          errors = {
            ...errors,
            utforandeVerksamheter: 'Minst en utförande verksamhet och adress behöver väljas',
          };
        }
      }

      return errors;
    };
  }
}
