import commonModule from '../';

describe('WsMultipleInputComponent', () => {
  let isolatedScope;
  let outerScope;
  let element;
  let $timeout;

  beforeEach(angular.mock.module(commonModule));

  function injectElement(elementHtml) {
    beforeEach(angular.mock.inject(($rootScope, $compile, _$timeout_) => {
      outerScope = $rootScope.$new();
      $timeout = _$timeout_;
      element = angular.element(elementHtml);
      $compile(element)(outerScope);
      isolatedScope = element.isolateScope();
      isolatedScope.$digest();
    }));
  }

  describe('initial state', () => {
    injectElement('<ws-multiple-input on-completed="onCompleted" number-of-inputs="3" is-readonly="false" />');

    it('should have created the right number of inputs', () => {
      const inputs = element.find('.ws-multiple-input');
      expect(inputs.length).toBe(3);
    });
  });

  describe('populating an input', () => {
    injectElement('<ws-multiple-input on-completed="onCompleted" number-of-inputs="3" is-readonly="false" />');

    it('should focus on next element', () => {
      const input0 = element.find('.ws-multiple-input')[0];
      const input1 = element.find('.ws-multiple-input')[1];
      spyOn(input1, 'focus');

      angular.element(input0).val('3');
      input0.dispatchEvent(new Event('keypress'));
      $timeout.flush();

      expect(input1.focus).toHaveBeenCalled();
    });
  });

  describe('using arrow keys', () => {
    injectElement('<ws-multiple-input on-completed="onCompleted" number-of-inputs="3" is-readonly="false" />');

    it('should focus on next element', () => {
      const input0 = element.find('.ws-multiple-input')[0];
      const input1 = element.find('.ws-multiple-input')[1];
      spyOn(input1, 'focus');

      const event = new Event('keydown');
      event.key = 'ArrowRight';
      event.initEvent('keydown');

      input0.dispatchEvent(event);
      outerScope.$digest();

      expect(input1.focus).toHaveBeenCalled();
    });
  });

  describe('numeric inputs only', () => {
    injectElement('<ws-multiple-input on-completed="onCompleted" is-numeric="true" number-of-inputs="3" is-readonly="false" />');

    it('doesnt allow alphabet character', () => {
      const input0 = element.find('.ws-multiple-input')[0];

      angular.element(input0).val('a');
      input0.dispatchEvent(new Event('keypress'));
      outerScope.$digest();

      expect(angular.element(input0).val()).toBe('');
    });

    it('allows numeric character', () => {
      const input0 = element.find('.ws-multiple-input')[0];

      angular.element(input0).val('3');
      input0.dispatchEvent(new Event('keypress'));
      outerScope.$digest();

      expect(angular.element(input0).val()).toBe('3');
    });
  });
});
