import { test } from 'ember-qunit';
import wait from 'ember-test-helpers/wait';
import moduleFor from 'web-client/tests/helpers/module-for';
import MockTrackingService from 'web-client/tests/helpers/mock-tracking-service';
import { createMockRouter } from 'web-client/tests/helpers/mock-routing-service';
import { pollTaskFor } from 'web-client/mixins/context-bound-tasks';
import TimeSpentClient from 'web-client/services/time-spent-client';

moduleFor('service:time-spent-client', 'Unit | Service | time-spent-client', {
  integration: false,
  needs: [
    'service:player-registry',
    'service:ember-user-activity@user-activity',
    'service:ember-user-activity@scroll-activity',
    'service:ajax',
    'service:vodResumeWatching',
    'service:recs-holdout'
  ],
  beforeEach () {
    this.register('service:tracking', MockTrackingService);
    this.register('service:-routing', createMockRouter(() => '/directory/following'));
    this.container.lookup('service:-routing').set('currentRouteName', TimeSpentClient.proto().ENABLED_ROUTES[0]);
  }
});

export function timeSpentEventAsserter (assert) {
  return ({event, services, data}) => {
    assert.equal(event, 'time_spent', 'time_spent is tracked');
    assert.deepEqual(services, ['spade'], 'time_spent event is sent to spade only');
    assert.ok('is_active' in data, 'time_spent event data tracks is_active');
    assert.ok('is_video_playing' in data, 'time_spent event data tracks is_video_playing');
  };
}

test('it exists', function (assert) {
  assert.expect(1);
  let service = this.subject();
  assert.ok(service);
});

test('#monitor starts tracking', function (assert) {
  assert.expect(12);
  let service = this.subject();
  service.monitor();
  let eventAsserter = timeSpentEventAsserter(assert);
  return wait()
    .then(() => {
      assert.trackEvent('time_spent', eventAsserter, 'first event');
      pollTaskFor(service.MONITOR_TASK_NAME);
    })
    .then(wait)
    .then(() => {
      assert.trackEvent('time_spent', eventAsserter, 'second event');
    });
});

test('#sendPayload() sends a tracking event', function (assert) {
  assert.expect(5);
  let service = this.subject();
  let eventAsserter = timeSpentEventAsserter(assert);
  return service.sendPayload().then(sent => {
    assert.ok(sent);
    assert.trackEvent('time_spent', eventAsserter);
  });
});

test("#sendPayload() doesn't send a tracking event if not on enabled route", function (assert) {
  assert.expect(1);
  this.container.lookup('service:-routing').set('currentRouteName', 'disabledroute');
  let service = this.subject();
  service.sendPayload().then(sent => {
    assert.ok(!sent);
  });
});
