import { DOCUMENT } from "@angular/common";
import {
  Directive,
  HostListener,
  Inject,
  Input,
  Renderer2,
} from "@angular/core";

@Directive({
  selector: "[appContextMenu]",
})
export class ContextMenuDirective {
  @Input("appContextMenu") conextMenuId;
  private menuNode;

  constructor(
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document
  ) {}

  ngAfterViewInit() {
    this.menuNode = document.getElementById(this.conextMenuId);
    if (this.menuNode) {
      this.renderer.setStyle(this.menuNode, "position", "fixed");
      this.renderer.setStyle(this.menuNode, "z-index", "999");
      this.renderer.setStyle(this.menuNode, "display", "none");
    } else {
      console.warn("Can not find conext menu item: ", this.conextMenuId);
    }
  }

  @HostListener("contextmenu", ["$event"]) onClick($event) {
    $event.preventDefault();

    let menuRect = this.menuNode.getBoundingClientRect();
    let bodyRect = this.document.body.getBoundingClientRect();

    if (this.menuNode) {
      this.renderer.setStyle(this.menuNode, "display", "block");

      if (
        bodyRect.height <= $event.clientY + menuRect.height &&
        menuRect.height < bodyRect.height
      ) {
        this.renderer.setStyle(
          this.menuNode,
          "top",
          bodyRect.height - menuRect.height + "px"
        );
      } else {
        this.renderer.setStyle(this.menuNode, "top", $event.clientY + "px");
      }

      if (
        bodyRect.width <= $event.clientX + menuRect.width &&
        menuRect.width < bodyRect.width
      ) {
        this.renderer.setStyle(
          this.menuNode,
          "left",
          bodyRect.width - menuRect.width + "px"
        );
      } else {
        this.renderer.setStyle(this.menuNode, "left", $event.clientX + "px");
      }
    } else {
      console.warn("Can not find conext menu item: ", this.conextMenuId);
    }
  }

  @HostListener("document:click", ["$event"])
  clickout(event) {
    if (this.menuNode) {
      this.renderer.setStyle(this.menuNode, "display", "none");
    } else {
      console.warn("Can not find conext menu item: ", this.conextMenuId);
    }
  }
}
