import { DOCUMENT } from '@angular/common';
import { Directive, HostListener, Inject, Input, Renderer2 } from '@angular/core';
import { CordovaService } from '../services/cordova.service';

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

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

  @HostListener('contextmenu', ['$event']) onClick($event) {
    if (this.cordovaService.isOnApp()) {
      $event.preventDefault();
      return;
    }

    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', 'block');
    } else {
      console.warn('Can not find context menu item: ', this.conextMenuId);
      return;
    }

    $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');
    }
  }
}
