import { Component, EventEmitter, Input, Output } from '@angular/core';
import {
  ContextMenuItem,
  ContextMenuPosition,
} from '../../interfaces/components/context-menu/context-menu.interface';

@Component({
  selector: 'app-context-menu',
  templateUrl: './context-menu.component.html',
  styleUrls: ['./context-menu.component.scss'],
})
export class ContextMenuComponent {
  @Input() isVisible = false;
  @Input() items: ContextMenuItem[] = [];
  @Input() position: ContextMenuPosition = { x: 0, y: 0 };

  @Output() isVisibleChange = new EventEmitter<boolean>();

  eventsToClose: string[] = ['click', 'dblclick', 'wheel'];

  ngOnInit() {
    this.addContextMenuEvents();
  }

  ngOnDestroy() {
    this.removeContextMenuEvents();
  }

  addContextMenuEvents() {
    this.eventsToClose.forEach((event) => {
      window.addEventListener(event, () => this.closeContextMenu());
    });
  }

  removeContextMenuEvents() {
    this.eventsToClose.forEach((event) => {
      window.removeEventListener(event, () => this.closeContextMenu());
    });
  }

  closeContextMenu() {
    if (!this.isVisible) return;

    this.isVisible = false;
    this.isVisibleChange.emit(false);
  }
}
