import { Route, PreloadingStrategy, Router, RouteConfigLoadStart, RouteConfigLoadEnd } from "@angular/router";
import { Observable, timer, of } from "rxjs";
import { Injectable } from "@angular/core";
import { flatMap } from 'rxjs/operators';
import { CommonService } from '../common/common.service';
import { Platform } from '@ionic/angular';


@Injectable()
export class HMGPreloadingStrategy implements PreloadingStrategy {
  constructor(
    public cs: CommonService,
    public router: Router
  ) {
    //this.monitorModulesLazyLoading();
  }

  /* 
  show progress when loading lazy module starts
  by monitoring router event
  */
  public monitorModulesLazyLoading() {
    this.router.events.subscribe(event => {
      if (event instanceof RouteConfigLoadStart) {
        if (!event.route.data) {
          this.cs.startLoading();
        }
      } else if (event instanceof RouteConfigLoadEnd) {
        this.cs.stopLoading();
      }
    });
  }


  preload(route: Route, load: Function): Observable<any> {
    if (route.data && route.data.preload) {
      // console.log('preloading lazy :' + route.path + ' after :' + (route.data.delay || 0));
      return timer(route.data.delay || 0).pipe(flatMap(() => {
        // console.log('loading  lazy :' + route.path);
        return load();
      }));
    }
    return of(null);
  }
}
