import {Directive, ElementRef, Input, OnDestroy, OnInit, Renderer2} from "@angular/core";
import {TaskMagicService} from "@magic-xpa/angular";
import {getGuiEventObj, IGuiEvent} from "@magic-xpa/engine";
import { Subscription } from "rxjs";
import {GuiConstants} from "@magic-xpa/gui";

/**
 * @ignore
 */
@Directive({
  selector: '[rowWithKeyBoardSelection]'
})
export class RowWithKeyBoardSelectionDirective implements OnInit, OnDestroy {
  @Input('magicRow') rowId: string = '';

  /**
   * @ignore
   */
  private rowChangedSubscriber!: Subscription;

  /**
   * The HTML element connected to this directive
   */
  protected htmlElement: HTMLElement;

  constructor(
    protected _task : TaskMagicService,
    protected element: ElementRef,
    protected renderer: Renderer2)
  {
    this.htmlElement = this.element.nativeElement;
  }

  /**
   * Initializes this object
   */
  ngOnInit(): void {
    this.regEvents();

    this.rowChangedSubscriber = this._task
      .OnSelectedRowChanged.subscribe(rowId => {
          if (rowId === this.rowId) {
            this.htmlElement.tabIndex = 0;
            this.htmlElement.focus();
          }
          else
          {
            this.htmlElement.tabIndex = -1;
          }
        }
      );
  }

  /**
   * Cleanup
   */
  ngOnDestroy() {
    if (this.rowChangedSubscriber !== null && this.rowChangedSubscriber !== undefined) {
      this.rowChangedSubscriber.unsubscribe();
    }
  }

  private regEvents() {
    this.renderer.listen(this.htmlElement, "keydown", (e: KeyboardEvent) => {
      let guiEvent: IGuiEvent = getGuiEventObj("navigateInTable", "magicRow", +this.rowId);

      let supportedKey = e.keyCode === GuiConstants.KEY_PG_UP ||
        e.keyCode === GuiConstants.KEY_PG_DOWN ||
        e.keyCode === GuiConstants.KEY_UP ||
        e.keyCode === GuiConstants.KEY_DOWN ||
        e.keyCode === GuiConstants.KEY_HOME ||
        e.keyCode === GuiConstants.KEY_END;

      if (supportedKey) {
        let evt = "";
        let ctrlPressed = false;

        if (e.ctrlKey && e.keyCode !== GuiConstants.KEY_CTRL)
          ctrlPressed = true;

        switch (e.keyCode) {
          case GuiConstants.KEY_PG_UP:
            evt = "previous-page";
            break;

          case GuiConstants.KEY_PG_DOWN:
            evt = "next-page";
            break;

          case GuiConstants.KEY_UP:
            evt = "previous-line";
            break;

          case GuiConstants.KEY_DOWN:
            evt = "next-line";
            break;

          case GuiConstants.KEY_HOME:
            if (ctrlPressed)
              evt = "begin-table";
            break;

          case GuiConstants.KEY_END:
            if (ctrlPressed)
              evt = "end-table";
            break;
        }

        if (evt !== "") {
          e.cancelBubble = true;
          e.preventDefault();

          guiEvent.Value = evt;
          this._task.insertEvent(guiEvent);
        }
      }
    });
  }
}