import { Directive, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core';
export enum SCROLLEND_DIRECTION {
  DOWN = 'down',
  UP = 'UP',
}

@Directive({
  selector: '[diunabiScrollEnd]',
  standalone: true,
})
export class ScrollEndDirective implements OnInit, OnDestroy {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  @Output() diunabiScrollEnd: EventEmitter<any> = new EventEmitter();

  @Input() rootMargin = '0px 0px 0px 0px';
  @Input() desiredDirection: SCROLLEND_DIRECTION = SCROLLEND_DIRECTION.DOWN;

  observer?: IntersectionObserver;
  previousEntry?: IntersectionObserverEntry;
  scrollDirection?: SCROLLEND_DIRECTION;

  constructor(
    private el: ElementRef,
  ) { }

  ngOnInit(): void {
    this.observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {
            this.scrollDirection = this.previousEntry?.boundingClientRect.bottom ?? 0 > entry.boundingClientRect.bottom ? SCROLLEND_DIRECTION.DOWN : SCROLLEND_DIRECTION.UP;
            if (!this.previousEntry?.isIntersecting && entry.isIntersecting && this.scrollDirection === this.desiredDirection) {
                this.diunabiScrollEnd.emit();
            }
            this.previousEntry = entry;
        });
    }, {
        rootMargin: this.rootMargin,
    });
    this.observer.observe(this.el.nativeElement);
  }
  ngOnDestroy(): void {
    this.observer?.disconnect();
  }
}