import { Component, Renderer2, ViewChild } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { UiSearchboxInputDirective } from '@ui/searchbox';

@Component({
  selector: 'unit-test',
  template: `<input uiSearchboxInput />`,
})
class TestComponent {
  @ViewChild(UiSearchboxInputDirective, { read: UiSearchboxInputDirective })
  directive: UiSearchboxInputDirective;
}

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

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

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

  describe('setValue', () => {
    it('should set the value property on the nativeElement', fakeAsync(() => {
      fixture.detectChanges();

      const testValue = 'Test';
      component.directive.setValue(testValue);

      fixture.detectChanges();
      tick();

      const input = component.directive.nativeElement;

      expect(input.value).toEqual(testValue);
    }));
  });

  describe('blur event', () => {
    it('should set focused to false', fakeAsync(() => {
      fixture.detectChanges();
      spyOn(component.directive, 'onBlur').and.callThrough();

      const debugEl = fixture.debugElement.query(By.css('input[uiSearchboxInput]'));
      debugEl.triggerEventHandler('blur', {});
      fixture.detectChanges();
      tick();

      expect(component.directive.onBlur).toHaveBeenCalled();
      expect(component.directive.focused).toBe(false);
    }));
  });

  describe('focus event', () => {
    it('should set focused to true', fakeAsync(() => {
      fixture.detectChanges();
      spyOn(component.directive, 'onFocus').and.callThrough();

      const debugEl = fixture.debugElement.query(By.css('input[uiSearchboxInput]'));
      debugEl.triggerEventHandler('focus', {});
      fixture.detectChanges();
      tick();

      expect(component.directive.onFocus).toHaveBeenCalled();
      expect(component.directive.focused).toBe(true);
    }));
  });
});
