import { Directive, HostListener, Input } from '@angular/core';
import { NbDialogService } from '@nebular/theme';
import { ContextMenuComponent } from '../../ui/context-menu/context-menu.component';
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: NbDialogService,
  ) { }

  @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) {
    var alternativeTarget;
    if (this.onContextMenuOpening) {
      alternativeTarget = this.onContextMenuOpening(this.RightClickValue, this.RightClickMenuItems, event);
    }

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

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