import { moduleFor, test } from 'ember-qunit';

let service;

moduleFor('service:pubsub', 'Unit | Service | pubsub', {
  beforeEach() {
    service = this.subject({
      client: {
        subscriptions: 0,
        Listen() {
          this.subscriptions++;
        },
        Unlisten() {
          this.subscriptions--;
        }
      }
    });
  }
});

test('#on - will correctly subscribe and trigger pubsub events', function (assert) {
  assert.expect(2);
  service.on('test-event', () => assert.ok(true));
  assert.equal(service.get('client.subscriptions'), 1);
  service.trigger('test-event');
});

test('#on - will only listen to each pubsub event once', function (assert) {
  assert.expect(1);
  service.on('some-event', () => {});
  service.on('test-event', () => {});
  service.on('some-event', () => {});
  assert.equal(service.get('client.subscriptions'), 2);
});

test('#off - stop listening if there are no more event listeners', function (assert) {
  assert.expect(1);
  let handleEvent = () => {};
  service.on('some-event', handleEvent);
  service.off('some-event', handleEvent);
  assert.equal(service.get('client.subscriptions'), 0);
});

test('#parsePayload', function (assert) {
  assert.expect(2);
  let testObject = { ok: true };
  assert.deepEqual(service.parsePayload(JSON.stringify(testObject)), testObject);
  assert.equal(service.parsePayload('not json'), null);
});
