/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

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

@Directive({
  selector: '[elementSizeChange]',
})
export class ElementSizeChangeDirective implements OnInit, OnDestroy {
  @Output()
  elementSizeChange = new EventEmitter<ResizeObserverEntry>();

  @Input() elementSizeChangeDebounce?: number;

  debounceStamp = 0;

  private resizeObserver: ResizeObserver;

  constructor(private elementRef: ElementRef) {}

  ngOnInit() {
    this.resizeObserver = new ResizeObserver(elements => {
      const stamp = Date.now();
      if (
        !elements[0] ||
        (this.elementSizeChangeDebounce && stamp - this.debounceStamp < this.elementSizeChangeDebounce)
      )
        return;
      this.debounceStamp = stamp;
      this.elementSizeChange.emit(elements[0]);
    });
    this.resizeObserver.observe(this.elementRef.nativeElement);
  }

  ngOnDestroy() {
    this.resizeObserver.disconnect();
  }
}
