import { AfterContentInit, Directive, ElementRef, Input } from '@angular/core';
import { StateService } from '../../services/state.service';
import { DebounceTimer } from '../../utilities/timer-utils';

@Directive({
  selector: '[initFocus]'
})
export class InitFocusDirective implements AfterContentInit {

  @Input('initFocus') enable: boolean = true;

  private debounceTimer = new DebounceTimer(100, () => { this.focusOnInitInput(); })
  private failedCount = 0;

  public constructor(private el: ElementRef,
    private stateService: StateService
  ) { }

  public ngAfterContentInit() {
    this.debounceTimer.resetTimer();
  }

  private focusOnInitInput() {
    if (this.stateService.waitingForScreenLock) return;
    if (false === this.enable) { return; }
    if (this.failedCount < 5) {

      if (!this.el.nativeElement) {
        this.debounceTimer.resetTimer();
      }
      else {
        if (["INPUT", "TEXTAREA", "BUTTON"].indexOf(this.el.nativeElement.tagName) > -1) {
          this.el.nativeElement.focus();
        }
        else {
          const firstInput = this.el.nativeElement.querySelector('input:not([type="checkbox"]), textarea')
          if (firstInput) {
            firstInput.focus();
          }
          else {
            this.debounceTimer.resetTimer();
          }
        }
      }

      this.failedCount++;
    }
    else {

    }
  }
}
