import {Injectable} from '@angular/core';
import {FormGroup} from "@angular/forms";

@Injectable({
  providedIn: 'root'
})
export class FormHelperService {


  constructor() {
  }


  public reset(formGroup: FormGroup) {
    formGroup.reset();
  }

  public showControlError(formGroup: FormGroup, formControlName: string, errorType: string = null): boolean {
    if (formGroup.valid) {
      return false;
    }

    if ( formControlName == null ){
      if ( errorType ){
        return formGroup.errors ? formGroup.errors[errorType]: false;
      }else {
        return formGroup.invalid;
      }
    }

    let control = formGroup.get(formControlName);

    if ( !control.dirty || !control.touched ){
      return false;
    }

    let hasErrors = control.invalid;
    if (!hasErrors) {
      return false;
    }
    if (errorType == null) {
      return true;
    }
    return    control?.errors[errorType];

  }

  public getValue(formGroup: FormGroup, control: string) {
    return formGroup.get(control).value
  }


}
