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

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

/**
 * Custom directive that checks and calculates if the panel (next element sibling)
 * can be open above or bellow. This component automatically identifies if the target
 * it's in a modal context by searching for 'cdk-modal-pane' class.
 * Caution! This component doesn't take into consideration the height for modal
 * sections like 'actions'.
 */
@Directive({
  selector: '[bciDropdownPositionSetter]',
  standalone: true
})
export class BciDropdownPositionSetterDirective {
  /**
   * Defines if the panel has special styles for opening bellow
   */
  @Input() belowStyles = ``;

  /**
   * Defines if the panel has special styles for opening above
   */
  @Input() aboveStyles = `
    top: auto;
    bottom: 100%;
    transform: none;
  `;

  constructor(private renderer: Renderer2, private el: ElementRef) {}

  @HostListener('click') onClick(): void {
    const inputElementRect = this.el.nativeElement.getBoundingClientRect();
    const nextElement: Element = this.el.nativeElement.nextElementSibling;
    const existingModal = document.getElementsByClassName('cdk-overlay-pane');
    let nextElementRect: DOMRect;
    let spaceFromBetween: number;
    let bottomUnusedSpace: number;

    if(existingModal && existingModal.length > 0) {
      bottomUnusedSpace = innerHeight - existingModal[0].clientHeight - existingModal[0].getBoundingClientRect().top;
      spaceFromBetween = innerHeight - inputElementRect.top - bottomUnusedSpace;
    } else {
      spaceFromBetween = innerHeight - inputElementRect.top;
    }


    if(nextElement) {
      nextElementRect = nextElement.getBoundingClientRect();
      if(spaceFromBetween > nextElementRect.height) {
        this.renderer.setAttribute(nextElement, 'style', this.belowStyles);
      } else {
        this.renderer.setAttribute(nextElement, 'style', this.aboveStyles);
      }
    }
  }
}
