/*
 * Copyright (C) 2023 Robert Bosch GmbH Copyright (C) 2023 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Directive, ElementRef, Input, OnChanges } from '@angular/core';

@Directive({
  selector: '[bciMenuMaxHeight]',
})
export class MenuMaxHeightDirective implements OnChanges {

  // Holds boolean value which represents if menu is opened or closed
  @Input() bciMenuMaxHeight;

  constructor(private elementRef: ElementRef) {}

  ngOnChanges(): void {
    this.bciMenuMaxHeight && this.setMenuMaxHeight();
  }  

  setMenuMaxHeight(): void {
    const windowHeight = document.documentElement.clientHeight;
    const menuPosition = this.elementRef.nativeElement.getBoundingClientRect().top;
    let maxMenuHeight;
    if((windowHeight - menuPosition) < menuPosition) {
      maxMenuHeight = `max-height: calc(${menuPosition}px - 24px)`;
    }
    else { 
      maxMenuHeight = `max-height: calc(${windowHeight}px - ${menuPosition}px - 72px)`;
    }
    const menuPanel = document.querySelectorAll(".mat-mdc-menu-panel")[0];    
    if(!(menuPanel.className as string).includes('mat-menu-adjusted-height')) {
      const classList = (menuPanel.className as string).concat('mat-menu-adjusted-height');
      menuPanel.setAttribute('class', classList);
      menuPanel.setAttribute('style', maxMenuHeight);
    } 
  }

}
