/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Component, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ToggleButtonDirective } from './toggle-button.directive';

@Component({
  template: '<div bciToggleButton [active]="true"></div>',
})
class TestComponent {}

describe('ToggleButtonDirective', () => {
  let fixture: ComponentFixture<TestComponent>;
  let component: TestComponent;
  let directive: ToggleButtonDirective;
  let debugElement: DebugElement;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [TestComponent, ToggleButtonDirective],
      }).compileComponents();
      fixture = TestBed.createComponent(TestComponent);
      fixture.detectChanges();

      component = fixture.componentInstance;
      debugElement = fixture.debugElement.query(By.css('div'));
      directive = debugElement.injector.get(ToggleButtonDirective);
    })
  );

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should reflect toggle state with css class', () => {
    expect(directive.active).toBeTruthy();
    expect(debugElement.nativeElement.getAttribute('class')).toContain('commandbar-button-active');

    debugElement.triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(directive.active).toBeFalsy();
    expect(debugElement.nativeElement.getAttribute('class')).not.toContain('commandbar-button-active');

    debugElement.triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(directive.active).toBeTruthy();
    expect(debugElement.nativeElement.getAttribute('class')).toContain('commandbar-button-active');
  });

  it('should emit toggle state change on click', () => {
    const states = [];
    directive.toggle.subscribe((toggleState) => states.push(toggleState));
    expect(states).toEqual([]);

    debugElement.triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(states).toEqual([false]);

    debugElement.triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(states).toEqual([false, true]);
  });

  it('should not emit toggle state upon programmatic state change', () => {
    const states = [];
    directive.toggle.subscribe((toggleState) => states.push(toggleState));
    expect(states).toEqual([]);

    directive.active = false;
    fixture.detectChanges();

    expect(states).toEqual([]);

    directive.active = true;
    fixture.detectChanges();

    expect(states).toEqual([]);
  });
});
