import { AfterViewInit, Directive, ElementRef, EventEmitter, Host, OnDestroy, Output } from '@angular/core';

@Directive({selector: "[enterTheViewportNotifier]"})
export class EnterTheViewportNotifierDirective implements AfterViewInit, OnDestroy {
  @Output() visibilityChange: EventEmitter<string> = new EventEmitter<string>();
  private intersectionObserver: IntersectionObserver;

  constructor(@Host() private elementRef: ElementRef) {}

  ngAfterViewInit(): void {
    const options = {root: null,rootMargin: "0px",threshold: 0.0};
    this.intersectionObserver = new IntersectionObserver(this._callback, options);
    this.intersectionObserver.observe(this.elementRef.nativeElement);
  }

  ngOnDestroy() { if (this.intersectionObserver) this.intersectionObserver.disconnect();}	

  private _callback = (entries, observer) => {
    entries.forEach(entry => 
        this.visibilityChange.emit(entry.isIntersecting));
  };
}