import { Injectable, Inject, Injector } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { DOCUMENT } from '@angular/common';
import { take, filter } from 'rxjs/operators';
import { ContainerPositionStrategy } from '../../../core/overlay/strategies';
import { IsaOverlayRef } from '../../../core/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { ShelfFilterComponent } from '../overlays/shelf-filter/shelf-filter.component';

@Injectable({ providedIn: 'root' })
export class ShelfOverlayService {
  constructor(@Inject(DOCUMENT) private document: Document, private overlay: Overlay, private injector: Injector, private router: Router) {}

  openShelfFilter() {
    const positionStrategy = new ContainerPositionStrategy(this.document.querySelector('.content-body'), {
      left: 0,
      right: 0,
      bottom: -20,
    });

    const disposeOnNavigation = true;
    const overlayRef = this.overlay.create({
      positionStrategy,
      disposeOnNavigation,
    });

    const isaOverlayRef = new IsaOverlayRef(overlayRef);

    const injector = Injector.create({
      providers: [{ provide: IsaOverlayRef, useValue: isaOverlayRef }],
      parent: this.injector,
    });

    const componentPortal = new ComponentPortal(ShelfFilterComponent, undefined, injector);
    overlayRef.attach(componentPortal);

    if (disposeOnNavigation) {
      this.closeOnNavigation(overlayRef);
    }
  }

  private closeOnNavigation(overlayRef: OverlayRef) {
    this.router.events
      .pipe(
        filter((routerEvent) => routerEvent instanceof NavigationStart),
        take(1)
      )
      .subscribe(() => overlayRef.hasAttached() && overlayRef.dispose());
  }
}
