import { Injectable } from "@angular/core";
import { HttpErrorResponse, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";

import { Observable, throwError } from 'rxjs';
import { catchError } from "rxjs/operators";

import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const authToken = this.auth.getAuthorizationToken();
        let authReq: HttpRequest<any>;
        if (authToken) {
            authReq = req.clone({
                headers: req.headers.set('Authorization', authToken)
            });
        } else {
            authReq = req;
        }

        return next.handle(authReq).pipe(
            catchError((error: HttpErrorResponse) => {
                if (error.status && error.status == 401) {
                    this.auth.requestAuth();
                    return throwError(() => $localize`Authentication required`);
                }
                if (error.status && error.status == 403) {
                    return throwError(() => $localize`Permissions too low`);
                }
                return throwError(() => error);
             })
        );
    }
}