import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { UtilsService } from '../services/utils.service';
import { environment } from 'src/environments/environment';
import { TokenService } from '../services/token.service';

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptor implements HttpInterceptor {
  constructor(private utilsService:UtilsService,
              private token:TokenService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const tractable:boolean = (request.url.indexOf(environment.baseApiUrl) != -1);

    //tractem request
    if(tractable) {
        if(this.token.loggedIn) {
          request = request.clone({ headers: request.headers.set("Authorization", "Bearer " + this.token.get())});
        }
    }

    //tractem response
    return next.handle(request);
  }
}