import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {AppService} from '../services/app.service';
import {Authorization} from '../models/Authorization';
import {catchError} from "rxjs/operators";
import {Router} from "@angular/router";
import {MessageService} from "primeng/api";

@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {

    private token: string = "";

    constructor(
        private app: AppService, 
        private router: Router, 
        private messageService: MessageService) {
    }

    intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {

        this.app.onAuthorizationDone().subscribe((authorization: Authorization) => {
            if (authorization)
                this.token = "Auth-Token " + authorization.token;
        });

        // if (isDevMode())
        //     console.log(`*** Interceptor TOKEN: ${this.token} ***  CALLING URL: ${request.url}`);

        // Clone the request to add the new header
        const clonedRequest = request.clone({
            headers: request.headers
                .set("Cache-Control", "no-cache")
                .set("Pragma", "no-cache")
                .set("Expires", "Sat, 01 Jan 2000 00:00:00 GMT")
                .set("Authorization", this.token)
                .set("Content-Type", "application/json")
                .set("Content-Language", this.app.getLanguage() || "en")
        });

        return next.handle(clonedRequest).pipe(catchError(e => this.handleAuthError(e)));
    }

    // REF: https://stackoverflow.com/questions/46017245/how-to-handle-unauthorized-requestsstatus-with-401-or-403-with-new-httpclient/46017463
    private handleAuthError(err: any): Observable<any> {
        if (err.status === 401 || err.status === 403) {
            this.app.removeAuthorization();
            this.token = "";
            //navigate /delete cookies or whatever
            this.router.navigateByUrl(`/`);
            // if you've caught / handled the error, you don't want to rethrow it unless you also want downstream consumers to have to handle it as well.
           // return of(err.message); // or EMPTY may be appropriate here
            return throwError(err);
        }

        this.messageService.add({
            severity: 'error',
            summary: err.status,
            detail: "Server error"
        });

        return throwError(err);
    }
}
