import {Injectable} from '@angular/core';
import {AuthService} from '../service/auth.service';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, Subscriber} from 'rxjs';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return new Observable<HttpEvent<any>>(observer => {
            this.auth.authenticated().subscribe(result => {
                if (result) {
                    this.auth.getToken().subscribe(token => {
                        req = req.clone({
                            setHeaders: {
                                Authorization: `Bearer ${token}`
                            }
                        });
                        this.handle(observer, req, next);
                    });
                } else {
                    this.handle(observer, req, next);
                }
            });
        });
    }

    handle(observer: Subscriber<HttpEvent<any>>, req: HttpRequest<any>, next: HttpHandler): void {
        next.handle(req).subscribe(value => {
            observer.next(value);
        });
    }

}
