import { FormArray, FormControl, FormGroup } from "@angular/forms";
import Utils from "../filler/common/utils";

export class FormUtils {

  public static markAsDirty(form: FormGroup): void {
    Object.values(form.controls).forEach(control => {
      if (control instanceof FormGroup) {
        this.markAsDirty(control);
      } else if (control instanceof FormArray) {
        control.controls.forEach(formControl => formControl.markAsDirty());
      } else if (control instanceof FormControl) {
        control.markAsDirty();
        control.updateValueAndValidity({ onlySelf: true });
      }
    });
  }

  public static getDirtyValues(form: any) {
    let dirtyValues = {};

    Object.keys(form.controls)
      .forEach(key => {
        let currentControl = form.controls[key];

        if (currentControl.dirty) {
          if (currentControl.controls)
            dirtyValues[key] = this.getDirtyValues(currentControl);
          else
            dirtyValues[key] = currentControl.value;
        }
      });

    return dirtyValues;
  }

  public static isDirty(form): boolean {
    let dirtyValues = this.getDirtyValues(form);
    if (!dirtyValues) return false;
    if (Object.values(dirtyValues).length <= 0) return false;
    return true;
  }


}
