import { test } from 'ember-qunit';
import moduleForIntegration from 'web-client/tests/helpers/module-for-integration';
import run from 'ember-runloop';

let service;

moduleForIntegration('service:watched-channels', 'Integration | Service | watched channels', {
  beforeEach() {
    let adapter = this.container.lookup('adapter:watched-channel');

    adapter._getIndex('watched-channels').reset();

    window.localStorage.clear();

    service = this.subject();
    service.set('_maxLength', 3);

    run(() => {
      let store = service.get('store');

      store.createRecord('watched-channel', {
        id: '1', timestamp: new Date('January 1, 2015 01:00:00')
      }).save();

      store.createRecord('watched-channel', {
        id: '2', timestamp: new Date('January 1, 2015 02:00:00')
      }).save();
    });
  },

  afterEach() {
    service = null;
  }
});

test('`addChannel` considers maxLength and deletes old to make room for new', function (assert) {
  assert.expect(4);

  let done = assert.async();
  let store = service.get('store');

  run(() => {
    store.findAll('watched-channel').then(function (channels) {
      assert.equal(channels.get('length'), 2);
    });
  });

  run(() => {
    service.addChannel('3').then(() => service.addChannel('4'));
  });

  run(() => {
    store.findAll('watched-channel')
      .then(function (watchedChannels) {
        assert.equal(watchedChannels.get('length'), 3);
        assert.ok(!watchedChannels.findBy('id', '1'), 'channel 1 is old and deleted');
        assert.ok(watchedChannels.findBy('id', '4'), 'channel 4 is new and inserted');
        done();
      });
  });
});

test('`addChannel` updates timestamp for existing channel', function (assert) {
  assert.expect(3);

  let done = assert.async();
  let store = service.get('store');

  run(() => {
    store.findAll('watched-channel').then(function (channels) {
      assert.equal(channels.get('length'), 2);
    });
  });

  run(() => {
    service.addChannel('1');
  });

  run(() => {
    store.findAll('watched-channel')
      .then(function (watchedChannels) {
        assert.equal(watchedChannels.get('length'), 2);

        let c1 = watchedChannels.get('firstObject');
        let c2 = watchedChannels.get('lastObject');

        assert.ok(c2.get('timestamp') < c1.get('timestamp'), 'channel 1 has a more recent timestamp');
        done();
      });
  });
});
