import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
import { ToasterService } from './toaster.service';

@Injectable()
export class HelperService {

    constructor(
        private ts: ToasterService
    ) {
    }

    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);
                        }
                    });
                }
            });
    }

    handleHttpError(httpError: HttpErrorResponse): void {
        let message;
        message = httpError.error.errors ? httpError.error.errors[Object.keys(httpError.error.errors)[0]] : httpError.error.message;
        switch (httpError.status) {
            case 401:
                break;
            case 403:
                break;
            case 404:
                break;
            case 422:
                break;
            case 500:
                message = 'Internal server error';
                break;
            case 0:
                message = 'No internet connection.';
                break;
            default:
                break;
        }
        this.ts.error(message, 'Request Error');
    }

    oneItHttpResponse(response): void {
        if (response.status === 'error') {
            this.ts.error(response.errorDetails[0]);
            throw new Error('Error on success response');
        }
    }

}
