import { Directive, ElementRef, EventEmitter, HostListener, Input, Output, Renderer2 } from '@angular/core';

@Directive({
  selector: '[focusNav]'
})
export class FocusNavigatorDirective {


  focusTag: string = 'focusNav';
  @Input("focusNav")
  public set input_focusTag(value) {
    this.focusTag = 'focusNav_' + value;

  }
  @Output() focusNavHitLast = new EventEmitter<number>();


  constructor(private elementRef: ElementRef, private renderer: Renderer2
  ) { }
  ngOnInit() {
    this.renderer.addClass(this.elementRef.nativeElement, this.focusTag);
  }
  @HostListener('keydown', ['$event']) keyHandler(event: KeyboardEvent) {
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
      if (!event.repeat && false === (event.target as HTMLInputElement).disabled) {
        //(event.target as HTMLInputElement).disabled = true;
        //var inputList = document.getElementsByClassName(this.focusTag);//'d-none'
        //var inputList = document.querySelectorAll(`.${this.focusTag}:not(.d-none)`);
        var inputList = Array.from(
          document.querySelectorAll(`.${this.focusTag}`)
        ).filter(el => !el.closest('.d-none'));
        let index = 0;
        for (let i = 0; i < inputList.length; i++) {
          const element = inputList[i];
          if (element == this.elementRef.nativeElement) {
            index = i;
            break;
          }
        }

        do {

          index += event.key === 'ArrowDown' ? 1 : -1
          index = index == -1 ? 0 : index; //== inputList.length ? 0 : index;

          if (index == inputList.length) {
            this.focusNavHitLast.next(inputList.length - 1);
            break;
          }


          var inputElement = this.getFirstHtmlInputElement(inputList[index]);
          if (!inputElement.readOnly) inputElement.focus();


        } while (inputElement.readOnly);
        event.preventDefault();
      }
    }
  }

  private getFirstHtmlInputElement(target: Element): HTMLInputElement {
    if (target instanceof HTMLInputElement) {
      return (target as HTMLInputElement);
    } else {
      return this.getFirstHtmlInputElement(target.children[0]);
    }
  }


  // private setCursorPosition(position) {
  //   let input = this.input.nativeElement;
  //   if (input.setSelectionRange) {
  //     input.focus();
  //     input.setSelectionRange(position, position);
  //   } else if (input.createTextRange) {
  //     var range = input.createTextRange();
  //     range.collapse(true);
  //     range.moveEnd('character', position);
  //     range.moveStart('character', position);
  //     range.select();
  //   }
  // }
}
