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

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

  openRemissionListFilter() {
    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(RemissionListFilterComponent, 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());
  }
}
