import { Injectable } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';

@Injectable()
export class HelperService {

    validateAllFormFields(form?: any): void {
        const formObj = typeof form.form ? form.form : form;
        Object
            .keys(form.controls)
            .forEach(field => {
                const control = formObj.get(field);
                if (control instanceof FormControl) {
                    control.markAsDirty({onlySelf: true});
                    control.markAsTouched({onlySelf: true});
                } else if (control instanceof FormGroup) {
                    this.validateAllFormFields(control);
                } else if (control instanceof FormArray) {
                    control.controls.forEach(ctrl => {
                        if (ctrl instanceof FormControl) {
                            ctrl.markAsDirty({onlySelf: true});
                            ctrl.markAsTouched({onlySelf: true});
                        } else if (ctrl instanceof FormGroup) {
                            this.validateAllFormFields(ctrl);
                        }
                    });
                }
            });
    }

}
