import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';

@Injectable()
export class LoaderService {
    public loaderComplete: Observable<boolean>;

    private loaders: Set<Object> = new Set<Object>();
    private loaderCompleteSource: Subject<boolean> = new Subject<boolean>();

    constructor() {
        this.loaderComplete = this.loaderCompleteSource.asObservable();
    }
    public subscribeLoader(owner: Object): Subscription {
        if (this.loaders.size === 0) {
            this.loaderCompleteSource.next(false);
        }
        this.loaders.add(owner);
        // console.log('LoaderService', this.loaders.size, 'subscribe', owner);
        return new Subscription(() => {
            // console.log('LoaderService', this.loaders.size, 'unsubscribe', owner);
            const size: number = this.loaders.size;
            this.loaders.delete(owner);

            if (size !== this.loaders.size && this.loaders.size === 0) {
                // console.log('LoaderService', this.loaders.size, 'load complete', owner);

                this.loaderCompleteSource.next(true);
            }
        });
    }
}
