import { Injectable } from '@angular/core';
import { BehaviorSubject, asapScheduler } from 'rxjs';
import { distinctUntilChanged, map, observeOn } from 'rxjs/operators';

//  Provided by each <app-loader>, and given to every pipe inside it, however deep
@Injectable()
export class LoadingManager {
    //  Every pipe inside the loader, and whether it's loading right now
    private pipes = new Map<object, boolean>();
    private count = new BehaviorSubject<number>(0);

    //  Is anything inside the loader loading?  Delivered just after change detection, so the loader
    //  can change while its content is being checked
    readonly loading$ = this.count.pipe(
        map((count) => count > 0),
        distinctUntilChanged(),
        observeOn(asapScheduler),
    );

    register(pipe: object) {
        this.pipes.set(pipe, false);
    }

    unregister(pipe: object) {
        this.pipes.delete(pipe);
        this.update();
    }

    setLoading(pipe: object, loading: boolean) {
        this.pipes.set(pipe, loading);
        this.update();
    }

    private update() {
        let count = 0;
        this.pipes.forEach((loading) => {
            if (loading) {
                count++;
            }
        });
        this.count.next(count);
    }
}
