import { Component, ViewChild } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { UiSearchboxAutocompleteOptionDirective } from './ui-searchbox-autocomplete-option.directive';

@Component({
  selector: 'unit-test',
  template: ` <button uiSearchboxAutocompleteOption value="Unit Test"></button> `,
})
class TestComponent {
  @ViewChild(UiSearchboxAutocompleteOptionDirective, { read: UiSearchboxAutocompleteOptionDirective })
  option: UiSearchboxAutocompleteOptionDirective;
}

describe('UiSearchboxAutocompleteOptionDirective', () => {
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestComponent, UiSearchboxAutocompleteOptionDirective],
    }).compileComponents();

    fixture = TestBed.createComponent(TestComponent);
  });

  describe('registerOnSelect', () => {
    it('should register set the onSelect proeprty', fakeAsync(() => {
      fixture.detectChanges();
      tick();

      const functionToRegister = () => {};

      fixture.componentInstance.option.registerOnSelect(functionToRegister);

      expect(fixture.componentInstance.option.onSelect).toEqual(functionToRegister);
    }));
  });

  describe('select', () => {
    it('should call onSelect with the value', fakeAsync(() => {
      fixture.detectChanges();
      tick();

      spyOn(fixture.componentInstance.option, 'onSelect').and.callThrough();

      fixture.componentInstance.option.select();

      expect(fixture.componentInstance.option.onSelect).toHaveBeenCalledWith(fixture.componentInstance.option.value);
    }));
  });

  it('click on the option element should call select', fakeAsync(() => {
    fixture.detectChanges();
    tick();

    spyOn(fixture.componentInstance.option, 'onSelect').and.callThrough();

    fixture.debugElement.query(By.css('button')).nativeElement.click();

    tick();

    expect(fixture.componentInstance.option.onSelect).toHaveBeenCalled();
  }));
});
