import { Directive, HostListener, Input } from '@angular/core';
import { NbDialogService } from '@nebular/theme';
import { ContextMenuComponent } from '../../components/context-menu/context-menu.component';
import { RbjDialogService } from '../../services/rbj-dialog.service';
import { ContextMenuItem } from './context-menu-item.model';
import { Direction } from './direction.enum';
const ITEM_HEIGHT = 45;
@Directive({
  selector: '[RightClickMenu]',
})
export class RightClickMenuDirective {

  @Input() public RightClickMenuItems: ContextMenuItem[] = [];
  @Input() public RightClickValue: any; // Value to pass into callback
  @Input() onContextMenuOpening: (datum: any, rightClickMenuItems: ContextMenuItem[], event: MouseEvent) => any;

  constructor(
    private dialogService: RbjDialogService,
  ) { }

  @HostListener('contextmenu', ['$event']) contextMenuHandler(event: MouseEvent) {
    if (event.which === 3 && this.RightClickMenuItems && this.RightClickMenuItems.length > 0) {
      this.open(event);
      event.preventDefault();
    }
  }

  open(event: MouseEvent, direction: Direction = Direction.Auto) {
    let targetValue = this.RightClickValue;

    for (let i = 0; i < this.RightClickMenuItems.length; i++) {
      this.RightClickMenuItems[i] = new ContextMenuItem(this.RightClickMenuItems[i]);
    }

    if (this.onContextMenuOpening) {
      targetValue = this.onContextMenuOpening(this.RightClickValue, this.RightClickMenuItems, event);
    }

    const windowHeight = window.innerHeight;
    const itemHeight = this.RightClickMenuItems.filter(i => i.visible).length * ITEM_HEIGHT;
    const y = (event.y + itemHeight) > windowHeight ? (windowHeight - itemHeight) : event.y;

    this.dialogService.open(ContextMenuComponent, {
      backdropClass: "transparent",
      context: {
        Value: targetValue,
        X: event.x,
        Y: y,
        ContextMenuItems: this.RightClickMenuItems,
        Direction: direction,
      },
      closeOnBackdropClick: true,
    });
  }
}
