import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { StateManagementService } from '@services/state-management.service';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {

  constructor(
    private stateManagementService: StateManagementService
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(this.injectToken(request));
  }

  injectToken(request: HttpRequest<any>) {
    const token = this.stateManagementService.token;
    if (token) {
      const apiDomain = new RegExp('https://www.googleapis.com');
      if (apiDomain.test(request.url) === false) {
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${token}` // 'Bearer ' keyword already added from server
          }
        });
      }
    }
    return request;
  }
}
