import { Directive, OnInit, OnDestroy, Self, Inject } from '@angular/core';
import { Subject, fromEvent } from 'rxjs';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { debounceTime, takeUntil } from 'rxjs/operators';

@Directive({
  // tslint:disable-next-line: directive-selector
  selector: 'cdk-virtual-scroll-viewport'
})
export class CdkVirtualScrollViewportPatchDirective
  implements OnInit, OnDestroy {
  protected readonly destroySubject = new Subject();

  constructor(
    @Self()
    @Inject(CdkVirtualScrollViewport)
    private readonly viewportComponent: CdkVirtualScrollViewport
  ) {}

  ngOnInit() {
    fromEvent(window, 'resize')
      .pipe(debounceTime(10), takeUntil(this.destroySubject))
      .subscribe(() => this.viewportComponent.checkViewportSize());
  }

  ngOnDestroy() {
    this.destroySubject.next();
    this.destroySubject.complete();
  }
}
