import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {NGXLogger} from 'ngx-logger';

@Injectable({
  providedIn: 'root'
})
/**
 * The InterceptorService intercepts EVERY http event.
 */
export class InterceptorService implements HttpInterceptor {

  constructor(private logger: NGXLogger) {
  }

  /**
   * Intercepts every HTTP request and for example adds a token
   * @param req   http request
   * @param next  http response handler
   */
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // TODO get the real token
    const token = 'A_TOKEN';

    // the original request is immutable, so we need to clone it
    req = req.clone({
      setHeaders: {
        // FIXME e.g. if Bearer is used
        Authorization: `Bearer ${token}`
      }
    });

    this.logger.debug('Interceptor works');

    // pipe the response observable
    return next.handle(req).pipe(
      // perform a side effect for every emission on the source Observable
      // return an Observable that is identical to the source
      tap(event => {
        // check if it is the response message
        if (event instanceof HttpResponse) {
          // TODO so something if necessary
        }
      }, error => {
        // TODO handle error here
        this.logger.error('HTTP Response interception error', error);
      })
    );
  }
}
