// https://github.com/arthurvaverko/ngx-fill-height/tree/master/src/app/fill-height

import { Directive, AfterViewInit, Input, HostListener, ElementRef, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core';

@Directive({
  selector: '[of-auto-height]'
})
export class AutoHeightDirective implements OnInit, OnDestroy, AfterViewInit {
  @Input() key: string;
  @Input() footerElement = null;

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.calculateAndSetElementHeight();
  }

  constructor(
    private elementRef: ElementRef,
    private changeDetector: ChangeDetectorRef,
  ) {
  }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    this.calculateAndSetElementHeight();
  }

  ngOnDestroy(): void {
  }

  onVisible(event) {
    console.log('visibilitychange');
  }

  /**
   * forceCalculate
   */
  public forceCalculate() {
    this.calculateAndSetElementHeight();
  }

  private calculateAndSetElementHeight() {
    this.changeDetector.detectChanges();

    this.elementRef.nativeElement.style.overflow = 'auto';
    const windowHeight = window.innerHeight;
    const elementOffsetTop = this.getElementOffsetTop();
    const elementMarginBottom = this.elementRef.nativeElement.style.marginBottom;
    const footerElementMargin = this.getfooterElementMargin();

    this.elementRef.nativeElement.style.height = windowHeight - footerElementMargin - elementOffsetTop + 'px';
    console.log([windowHeight, elementOffsetTop, elementMarginBottom, footerElementMargin, this.elementRef.nativeElement.style.height]);
  }

  private getElementOffsetTop() {
    return this.elementRef.nativeElement.getBoundingClientRect().top;
  }

  private getfooterElementMargin() {
    if (!this.footerElement) { return 0; }
    const footerStyle = window.getComputedStyle(this.footerElement);
    return parseInt(footerStyle.height, 10);
  }
}
