import { Injectable } from '@angular/core';
import { Router, NavigationEnd, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LifeCycleService {

  constructor(
    public router: Router
  ) { }

  public pageRevisited(pageName: string): Observable<boolean> {
    return Observable.create(observer => {
      this.router.events.subscribe((val) => {
        if (this.isSamePage(val, pageName)) {
          observer.next(true);
          observer.complete();
        }
      });

    });
  }

  private isSamePage(val: any, pageName: string) {
    if (val instanceof NavigationEnd) {
      const lastIndex = val.urlAfterRedirects.lastIndexOf('/');
      const currentPageName = val.urlAfterRedirects.substr(lastIndex + 1);
      return currentPageName === pageName;
    }
    return false;
  }
}
