import moduleForIntegration from 'web-client/tests/helpers/module-for-integration';
import { test } from 'ember-qunit';
import { AuthenticatedSession } from 'web-client/tests/helpers/mock-session-service';
import { assign } from 'ember-platform';

const TOKEN = 'foobar';
const OauthSession = AuthenticatedSession.extend({
  userData: assign({chat_oauth_token: TOKEN}, AuthenticatedSession.prototype.userData)
});

moduleForIntegration('service:video-downloader', 'Integration | Service | Video Downloader', {
  beforeEach() {
    this.register('service:session', OauthSession);
  }
});

test('rate limits', function(assert) {
  assert.expect(2);

  this.server.get(
    'http://api.twitch.tv/kraken/vods/:videoId/download',
    { status: 'not_ready' }
  );

  let service = this.subject();
  service.set('downloadLimit', 1);

  return service.fetchDownload('123').then(() => {
    return service.fetchDownload('1234');
  }).then((response) => {
    assert.equal(response.status, 'rate_limited', 'rate limited');
    assert.equal(service.get('currentDownloads').has('123'), true, 'first video still downloading');
  });
});

test('failure removes from rate limiting', function(assert) {
  assert.expect(2);

  this.server.get(
    'http://api.twitch.tv/kraken/vods/:videoId/download',
    { status: 'failed' }
  );

  let service = this.subject();

  return service.fetchDownload('123').then((response) => {
    assert.equal(response.status, 'failed', 'failure propagates');
    assert.equal(service.get('currentDownloads').has('123'), false, 'video removed from downloads');
  });
});

test('propagates error', function(assert) {
  assert.expect(1);

  this.server.get(
    'http://api.twitch.tv/kraken/vods/:videoId/download',
    { status: 'not_ready' },
    401
  );

  let service = this.subject();

  return service.fetchDownload('123').then(() => {
    assert.equal(1,0, 'call should not succeed');
  }, (response) => {
    assert.equal(response.status, 401, 'errors');
  });
});
