import {Injectable, OnDestroy} from '@angular/core';
import {HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, Subscription, throwError} from 'rxjs';
import {Authorization} from '../models/Authorization';
import {catchError} from "rxjs/operators";
import {MessageService} from "primeng/api";
import {AuthService} from "../services/auth.service";
import {environment} from "../../environments/environment";
import {OAuthService} from "angular-oauth2-oidc";

@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor, OnDestroy {

    private token: string = "";
    private readonly authObserver?: Subscription ;

    constructor(
        private authService: AuthService,
        private oauthService: OAuthService,
        private messageService: MessageService) {
        this.authObserver = this.authService.onAuthChange().subscribe((authorization: Authorization) => {
            this.token = authorization?.authenticated ? "Auth-Token " + authorization?.token : "";
        });
    }

    ngOnDestroy(): void {
        if (this.authObserver)
            this.authObserver.unsubscribe()
    }

    intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        let clonedRequest  =  request.clone({
            headers: this.getHeaders(request)
        });

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

    private getHeaders(request: HttpRequest<unknown>): HttpHeaders {
        if (this.token) {
            return  request.headers
                .set("Authorization", this.token)
                .set("Content-Language", sessionStorage.getItem("lang") || "en")
        }
        else {
            return request.headers
                .set("Content-Language", sessionStorage.getItem("lang") || "en");
        }
    }

    private handleAuthError(err: any): Observable<any> {
        if (err.status === 401 || err.status === 403) {
            this.token = "";
            this.authService.removeAuthorization();
        }

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

        return throwError(err);
    }
}

