import { moduleFor, test } from 'ember-qunit';
import {
  setup as setupMirage, teardown as teardownMirage
} from 'web-client/tests/helpers/setup-mirage-for-integration';
import run from 'ember-runloop';

moduleFor('adapter:channel', 'Integration | Adapter | Channel', {
  integration: true,
  beforeEach() {
    setupMirage(this);
  },
  afterEach() {
    teardownMirage(this);
  }
});

test('channel find uses correct url', function(assert) {
  assert.expect(1);

  let url = `https://api.twitch.tv/api/channels/hello/ember`;
  this.server.get(url, function() {
    assert.ok(true, `find sent query to ${url}`);
  });

  run(() => {
    let store = this.container.lookup('service:store');
    store.findRecord('channel', 'hello');
  });
});

test('channel is cached before expiry', function(assert) {
  assert.expect(2); // 2, not 3, the middle findRecord is cached.

  let done = assert.async();
  let store = this.container.lookup('service:store');
  let channel = this.server.create('channel-ember-data', { name: 'hello' });

  this.server.get(`https://api.twitch.tv/api/channels/hello/ember`, function() {
    assert.ok(true, `find sent query to adapter`);
    return channel;
  });

  run(() => {
    store.findRecord('channel', 'hello');
  });

  run.later(() => {
    store.findRecord('channel', 'hello');
  }, 10);

  run.later(() => {
    store.findRecord('channel', 'hello').then(() => {
      done();
    });
  }, 150);
});

test('channel hasMany following uses correct url', function(assert) {
  assert.expect(1);

  let url = 'https://api.twitch.tv/kraken/users/hello/follows/channels';
  this.server.get(url, function() {
    assert.ok(true, `findHasMany sent query to ${url}`);
  });

  let channelEmberData = this.server.create('channel-ember-data', { name: 'hello' });
  let store = this.container.lookup('service:store');
  let serializer = store.serializerFor('channel');
  let data = serializer.normalizeResponse(store, 'channel', channelEmberData, null, 'findRecord');

  run(() => {
    let model = store.push(data);
    model.get('following');
  });
});
