import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { finalize, Observable } from 'rxjs';
import { DataService } from '../services/data.service';

@Injectable()
export class LoaderInterceptor implements HttpInterceptor {

  private tasks = 0;

  constructor(
    private data$: DataService
  ) { }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    this.addTask();
    return next.handle(request).pipe(
      finalize(() => {
        this.removeTask();
      })
    );
  }

  addTask() {
    this.tasks++;
    if (this.tasks === 1) {
      this.data$.showLoader.next(true);
    }
  }

  removeTask() {
    this.tasks--;
    if (this.tasks === 0) {
      this.data$.showLoader.next(false);
    }
  }
}
