import { Injectable } from '@angular/core';
import { AbstractControl, FormControl, FormGroup } from '@angular/forms';
import { RoleEnum } from '@msfa-enums/role.enum';
import { Role } from '@msfa-models/role.model';
import { Tjanst } from '@msfa-models/tjanst.model';

@Injectable({
  providedIn: 'root',
})
export class EmployeeFormService {
  isSelectedRole(role: Role, selectedRoles: RoleEnum[]): boolean {
    if (!selectedRoles || !role) {
      return false;
    }

    return selectedRoles.some(selectedRole => selectedRole === role.type);
  }

  getSelectedTjanster(tjanster: Array<Tjanst>, tjanstId: number): Array<Tjanst> {
    let selectedTjanst: Tjanst | null = null;

    if (!tjanster) {
      return [];
    }

    selectedTjanst = tjanster.find(tjanst => tjanst.tjanstId === tjanstId);

    return selectedTjanst ? [selectedTjanst] : [];
  }

  getRolesFromFormGroup(formGroup: AbstractControl | null, roles: Array<Role> | null): Array<RoleEnum> {
    if (!formGroup || !roles) {
      return;
    }

    return roles.filter(role => formGroup.get(this.getFormControlName(role))?.value).map(role => role.type);
  }

  getRolesFormGroup(roles: Array<Role> | null, selectedRoles: RoleEnum[]): FormGroup {
    if (!roles) {
      return new FormGroup({});
    }

    return new FormGroup(
      Object.fromEntries(
        roles.map(role => [
          this.getFormControlName(role),
          new FormControl(this.isSelectedRole(role, selectedRoles), []),
        ])
      )
    );
  }

  getFormControlName(role: Role): string {
    return RoleEnum[role?.type];
  }
}
