import { ErrorHandler, Inject, Injectable, Injector } from '@angular/core';
import { HttpErrorResponse, HttpStatusCode } from '@angular/common/http';
import { Toaster } from '@iqser/common-ui';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';

@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
    constructor(@Inject(Injector) private _injector: Injector) {
        super();
    }
    handleError(error: Error): void {
        const chunkFailedMessage = /Loading chunk [\d]+ failed/;
        console.write(error);
        if (error.name === 'HttpErrorResponse') {
            const err = error as HttpErrorResponse;
            if (err.status >= HttpStatusCode.BadRequest && err.status <= HttpStatusCode.InternalServerError) {
                const toaster = this._injector.get(Toaster);
                if (err.error.message) {
                    toaster.rawError(err.error.message);
                } else if ([400, 403, 404, 409, 500].includes(err.status)) {
                    toaster.rawError(_(`generic-errors.${err.status}`));
                }
            }
        }

        if (error?.message?.includes('An error happened during access validation')) {
            console.log('User is not authorized to access this page');
        }

        if (chunkFailedMessage.test(error?.message)) {
            window.location.reload();
        }

        return super.handleError(error);
    }
}
