import { Component, ViewChild, Input, AfterViewInit, ElementRef } from '@angular/core';
import { NbDialogRef, NbDialogService } from '@nebular/theme';
import { ContextMenuItem } from '../../directives/right-click-menu/context-menu-item.model';
import { Direction } from '../../directives/right-click-menu/direction.enum';
import { RbjDialogService } from '../../services/rbj-dialog.service';

@Component({
  selector: 'ngx-context-menu',
  templateUrl: './context-menu.component.html',
  styleUrls: ['./context-menu.component.scss']
})
export class ContextMenuComponent implements AfterViewInit {

  @ViewChild('menu') menu: ElementRef;

  selectedItem: string;

  @Input() public Value: any;
  @Input() public X: number;
  @Input() public Y: number;

  ContextMenuItems: ContextMenuItem[];

  @Input() public Direction: Direction;

  constructor(
    protected ref: NbDialogRef<ContextMenuComponent>,
    private dialogService: RbjDialogService,
  ) { }

  ngAfterViewInit(): void {
    this.menu.nativeElement.style.position = "absolute";
    this.menu.nativeElement.style.left = this.X + 'px';
    this.menu.nativeElement.style.top = this.Y + 'px';

    // switch (this.Direction) {
    //   case Direction.Auto:
    //   case Direction.Down:
    //     this.menu.nativeElement.style.left = this.X + 'px';
    //     this.menu.nativeElement.style.top = this.Y + 'px';
    //   case Direction.Up:
    //     this.menu.nativeElement.style.left = this.X + 'px';
    //     this.menu.nativeElement.style.bottom = this.Y + 'px';
    //   case Direction.Left:
    //     this.menu.nativeElement.style.left = this.X + 'px';
    //     this.menu.nativeElement.style.top = this.Y + 'px';
    //   case Direction.Right:
    //     this.menu.nativeElement.style.left = this.X + 'px';
    //     this.menu.nativeElement.style.top = this.Y + 'px';
    // }
  }

  runItemCallback(item: ContextMenuItem, event: any) {

    if (item.contextMenuItems) {
      this.dialogService.open(ContextMenuComponent, {
        backdropClass: "transparent",
        context: {
          Value: this,
          X: this.X + this.menu.nativeElement.width,
          Y: event.y - event.offsetY,
          ContextMenuItems: item.contextMenuItems,
          Direction: Direction.Right,
        },
        closeOnBackdropClick: true,
      });
    }
    else {
      this.ref.close();
      setTimeout(() => item && item.callback && item.callback(this.Value, event.target as HTMLElement));
    }
  }

}
