import { Directive, ElementRef, HostListener, Input, Inject, Renderer2 } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Directive({ selector: '[appUiDropdownItem]' })
export class UiDropdownItemDirective {
  get nativeElement(): HTMLElement {
    return this.elementRef.nativeElement;
  }

  @Input()
  value: any;

  @Input()
  set selected(isSelected: boolean) {
    this.setSelected(isSelected);
  }

  get focused() {
    return this.nativeElement === document.activeElement;
  }

  onSelect = (value) => {};

  constructor(private elementRef: ElementRef, private renderer: Renderer2, @Inject(DOCUMENT) private document: Document) {}

  registerOnSelect(fn: any) {
    this.onSelect = fn;
  }

  focus() {
    setTimeout(() => this.nativeElement.focus(), 10);
  }

  setSelected(isSelected: boolean): void {
    if (isSelected) {
      this.renderer.addClass(this.nativeElement, 'selected');
      this.nativeElement.focus();
    } else {
      this.renderer.removeClass(this.nativeElement, 'selected');
    }
  }

  @HostListener('click')
  click() {
    this.onSelect(this.value);
  }
}
