import { ChangeDetectorRef, Directive, ElementRef, HostListener, Input, Renderer2 } from '@angular/core';
import { NbAdjustment, NbDynamicOverlay, NbDynamicOverlayHandler, NbPosition, NbTrigger } from '@nebular/theme';
import { first } from 'rxjs/operators';
import { RbjTooltipService } from '../../services/rbj-tooltip.service';
import { TextareaUtils } from '../../utilities/textarea-utils';
import { DebounceTimer } from '../../utilities/timer-utils';
import { UuidUtils } from '../../utilities/uuid-utils';
import { PopoverMsgComponent } from './popover-msg/popover-msg.component';

@Directive({
  selector: '[inputLimitation]',
  providers: [
    NbDynamicOverlayHandler,
    NbDynamicOverlay
  ],
})
export class InputLimitationDirective {
  @Input('inputLimitation') inputLimitation: number = null;
  private debounceTimer = new DebounceTimer(100, () => { this.setInputLimitForElement(); })
  uuid: string;

  public get message(): string {
    return `The input limit of this field is ${this.inputLimitation} characters`
  }


  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2,
    private rbjTooltipService: RbjTooltipService
  ) { }

  @HostListener('keydown', ['$event'])
  public onKeyDown(e: KeyboardEvent): void {
    if (this.inputLimitation) {
      const el: HTMLInputElement = e.target as HTMLInputElement;
      let isReplacing = el.selectionStart != el.selectionEnd;

      if (false == isReplacing && el.value.length >= this.inputLimitation && TextareaUtils.isEditingKeyPress(e)) {
        this.showLimitation();
      }
    }
  }

  showLimitation() {
    this.rbjTooltipService.show(this.elementRef, this.message, this.uuid);

  }
  ngOnInit() {
    this.uuid = UuidUtils.generate();
  }

  ngAfterViewInit() {
    this.setInputLimitForElement();
  }
  ngOnDestroy() {
    this.rbjTooltipService.destroy(this.uuid);
  }
  private failedCount: number = 0;
  private setInputLimitForElement() {
    if (this.inputLimitation > 0 && this.failedCount < 5) {
      if (!this.elementRef.nativeElement) {
        this.debounceTimer.resetTimer();
      }
      else {
        if (["INPUT", "TEXTAREA"].indexOf(this.elementRef.nativeElement.tagName) > -1) {
          this.elementRef.nativeElement.setAttribute('maxlength', this.inputLimitation.toString());
        }
        else {
          const firstInput = this.elementRef.nativeElement.querySelector('input:not([type="checkbox"]), textarea')
          if (firstInput) {
            firstInput.setAttribute('maxlength', this.inputLimitation.toString());
          }
          else {
            this.debounceTimer.resetTimer();
          }
        }
      }

      this.failedCount++;
    }
  }
}
