import moduleFor from 'web-client/tests/helpers/module-for';
import sinonTest from 'ember-sinon-qunit/test-support/test';
import run from 'ember-runloop';
import { FakeExperimentService } from 'web-client/tests/helpers/experiment-group-test';

let service;

moduleFor('service:cdn-metrics', 'Unit | Service | CDN Metrics', {
  beforeEach() {
    this.owner.register('service:experiments', FakeExperimentService);
    service = this.subject();
  }
});

sinonTest('cdnExperiment starts after a delay', function (assert) {
  assert.expect(2);
  this.owner.lookup('service:experiments').use({ NEXUS_ROLLOUT: 'enabled' });

  // Expect service.runTask to be called once with a 5 minute delay.
  // Since this is a test, call the function immediately instead of waiting.
  this.stub(service, 'runTask', (callback, delay) => {
    assert.equal(delay, service.get('POLL_INTERVAL'));

    let stub = this.stub(service, '_runCDNExperiment');
    run(service, callback);
    assert.ok(stub.calledWithExactly());
  });

  service.monitor();
});

sinonTest('cdnExperiment respects the NEXUS_ROLLOUT experiment', function (assert) {
  assert.expect(2);
  this.owner.lookup('service:experiments').use({ NEXUS_ROLLOUT: 'disabled' });

  // Expect service.runTask to be called once with a 5 minute delay.
  // Since this is a test, call the function immediately instead of waiting.
  this.stub(service, 'runTask', (callback, delay) => {
    assert.equal(delay, service.get('POLL_INTERVAL'));

    let stub = this.stub(service, '_runCDNExperiment');
    run(service, callback);
    assert.notOk(stub.called);
  });

  service.monitor();
});

sinonTest('_chooseAssets loops through the assets in SAMPLE_SIZE chunks', function (assert) {
  assert.expect(1);

  service.set('assets', ['a', 'b', 'c', 'd', 'e', 'f', 'g']);
  service.set('SAMPLE_SIZE', 3);

  let samples = [
    service._chooseAssets(),
    service._chooseAssets(),
    service._chooseAssets(),
    service._chooseAssets(),
    service._chooseAssets(),
    service._chooseAssets()
  ];

  assert.deepEqual(samples, [
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['g', 'a', 'b'],
    ['c', 'd', 'e'],
    ['f', 'g', 'a'],
    ['b', 'c', 'd']
  ]);
});
