import { Directive, HostListener, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { BranchDTO } from '@swagger/checkout';
import { PurchasingOptionsModalStore } from '../../modals/purchasing-options-modal/purchasing-options-modal.store';

/* tslint:disable: directive-selector */
@Directive({ selector: '[keyNavigation]' })
export class KeyNavigationDirective implements OnInit {
  @Input() element: any;
  @Input('keyNavigation') data: BranchDTO[];
  @Output() closeDropdown = new EventEmitter<void>();
  @Output() preselectBranch = new EventEmitter<BranchDTO>();
  selectedData: BranchDTO;
  position = 0;
  posMarker = 0;

  @HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    if (event.key === 'ArrowUp') {
      if (this.position > 0) {
        this.position--;
      }

      if (this.position <= this.posMarker - 4) {
        this.element.scrollTop -= 44;
      }

      this.selectedData = this.data[this.position];
      this.preselectBranch.emit(this.selectedData);
    }

    if (event.key === 'ArrowDown') {
      if (this.position < this.data.length - 1) {
        this.position++;
      }

      if (this.position >= 4) {
        this.posMarker = this.position;
        this.element.scrollTop += 44;
      }

      this.selectedData = this.data[this.position];
      this.preselectBranch.emit(this.selectedData);
    }

    if (event.key === 'Enter') {
      this.purchasingOptionsModalStore.setBranch(this.selectedData);
      this.position = 0;
      this.closeDropdown.emit();
    }
  }

  constructor(private purchasingOptionsModalStore: PurchasingOptionsModalStore) {}

  ngOnInit() {
    this.selectedData = this.data[this.position];
    this.preselectBranch.emit(this.selectedData);
  }
}
