/* globals describe, it, before */
"use strict";

var chai = require("chai"),
    assert = chai.assert,
    chaiAsPromised = require("chai-as-promised"),
    sinon  = require("sinon");

var utils = require("radiodan-client").utils;

chai.use(chaiAsPromised);

var BBCServices = require("../../lib/bbc-services");

describe("cache", function(){
  it("stores data", function(){
    var data = {a: "b"},
        subject = BBCServices.create();

    subject.cacheStore("station1", "data", data);

    assert.equal(subject.cache["station1"]["data"], data);
  });
});

describe("on eventstream", function(){
  beforeEach(function() {
    var noOp = function(){},
        nullLog = {error: noOp, debug: noOp, warn: noOp};

    this.subject = BBCServices.create(nullLog),
    this.eventMock = {};

    this.subject.listenForEvents(this.eventMock);
  });

  it("resolves ready promise when first message arrives", function(done){
    this.eventMock.onmessage({});

    assert.isFulfilled(this.subject.ready).then(done);
  });

  it("stores data in cache", function(done){
    var self = this,
        data = {service: "radio1", topic: "liveData", data: {"a": "b"}};

    this.eventMock.onmessage({data: JSON.stringify(data)});

    assert.isFulfilled(self.subject.ready)
      .then(function(){
        var cached = self.subject.cache["radio1"]["liveData"];
        assert.deepEqual(data.data, cached);
      })
      .then(done, done);
  });

  it("emits events from recieved topic", function(done){
    var self = this,
        data = {service: "1xtra", topic: "nowPlaying", data: {"a": "b"}},
        stationPromise = utils.promise.defer(),
        topicPromise = utils.promise.defer();

    self.subject.once("1xtra", function(topic, emitData) {
      assert.deepEqual(data.topic, topic);
      assert.deepEqual(data.data, emitData);

      stationPromise.resolve();
    });

    self.subject.once("1xtra/nowPlaying", function(emitData) {
      assert.deepEqual(data.data, emitData);

      topicPromise.resolve();
    });

    this.eventMock.onmessage({data: JSON.stringify(data)});

    assert.isFulfilled(stationPromise.promise)
      .then(function(){
        return assert.isFulfilled(topicPromise.promise);
      })
      .then(done,done);
  });
});

@@ -844,179 +844,8 @@
 );%0A%0A
-  it(%22resolves ready promise when first message arrives%22, function(done)%7B%0A    this.eventMock.onmessage(%7B%7D);%0A%0A    assert.isFulfilled(this.subject.ready).then(done);%0A  %7D);%0A%0A
   it
@@ -870,36 +870,32 @@
 ache%22, function(
-done
 )%7B%0A    var self 
@@ -973,16 +973,32 @@
 %22: %22b%22%7D%7D
+,%0A        cached
 ;%0A%0A    t
@@ -1061,83 +1061,8 @@
     
-assert.isFulfilled(self.subject.ready)%0A      .then(function()%7B%0A        var 
 cach
@@ -1108,20 +1108,16 @@
 Data%22%5D;%0A
-    
     asse
@@ -1153,42 +1153,8 @@
 d);%0A
-      %7D)%0A      .then(done, done);%0A
   %7D)

Remove promise dependency from BBCServices test