import { Injectable} from '@angular/core';
import { PreloadingStrategy,Route } from '@angular/router'
import { Observable, EMPTY } from 'rxjs';
import { PackageService} from './package.service';

@Injectable({
    providedIn: 'root',
  })
export class PackagePreloadStrategy extends PreloadingStrategy {

    loading = new Set<Route>();

    constructor(private packageService$:PackageService) {
        super();
    }

    preload(route: Route, load: Function): Observable<any> {
        if (this.loading.has(route)) {
            // Don't preload the same route twice
            return EMPTY;
        }
        if(route.data && route.data.package) {
            if(this.packageService$.hasPackage(route.data.package)) {
                //console.debug(`Load module for package ${route.data.package}`)
                this.loading.add(route);
                return load()
            }
        }
        return EMPTY;
    }
}