var Logger = require('js-logger'),
    extend = require('underscore').extend,
    clone  = require('underscore').clone,
    EventEmitter  = require('events').EventEmitter,
    AppDispatcher = require('../dispatcher/dispatcher'),
    CurrentServiceStore = require('../stores/current-service'),
    Payload   = require('../constants/constants').Payload,
    ActionTypes   = require('../constants/constants').ActionTypes;

var state = {};

function convertStringsToDates(datum) {
  if (datum.start) {
    datum.start = new Date(datum.start);
  }
  if (datum.end) {
    datum.end = new Date(datum.end);
  }
  return datum;
}

function update(id, data) {
  Logger.debug('NowAndNext update', id, data);
  data.forEach(convertStringsToDates);
  state[id] = data;
}

var Store = extend(new EventEmitter(), {
  get: function (id) {
    if (state[id]) {
      return clone(state[id]);
    }
  },
  emitChange: function (id) {
    this.emit('change', id);
  },
  addChangeListener: function (callback) {
    this.on('change', callback);
  }
});

Store.dispatchToken = AppDispatcher.register(function (payload) {
  var source = payload.source,
      action = payload.action;

  switch(action.type) {
    case ActionTypes.RECEIVE_INITIAL_STATE:
      AppDispatcher.waitFor([CurrentServiceStore.dispatchToken]);
      Logger.debug('NowAndNext', action.type, action.state);
      if (action.state.current && action.state.current.nowAndNext) {
        update(action.state.current.id, action.state.current.nowAndNext);
        Store.emitChange(action.state.current.id);
      }
      break;
    case ActionTypes.SERVICE:
      Logger.debug('NowAndNext: ', action.type, action.state);
      if (source === Payload.SERVER_ACTION) {
        AppDispatcher.waitFor([CurrentServiceStore.dispatchToken]);
        Logger.debug('NowAndNext: SERVER', action.type, action.state);
        if (action.state.data && action.state.data.nowAndNext) {
          update(action.state.data.id, action.state.data.nowAndNext);
          Store.emitChange(action.state.data.id);
        }
      }
      break;
    case ActionTypes.NOW_AND_NEXT:
      Logger.debug('NowAndNext: ', action.type, action.state);
      if (source === Payload.SERVER_ACTION) {
        Logger.debug('NowAndNext: SERVER', action.type, action.state);
        if (action.state.service && action.state.data) {
          update(action.state.service, action.state.data);
          Store.emitChange(action.state.service);
        }
      }
      break;
  }
});

module.exports = Store;
@@ -1619,32 +1619,40 @@
 ebug('NowAndNext
+.SERVICE
 : ', action.type
@@ -2134,16 +2134,29 @@
 wAndNext
+.NOW_AND_NEXT
 : ', act
@@ -2313,32 +2313,8 @@
 if (
-action.state.service && 
 acti
@@ -2360,23 +2360,30 @@
 n.state.
+data.
 service
+Id
 , action
@@ -2389,24 +2389,40 @@
 n.state.data
+.nowAndNext.data
 );%0A         
@@ -2452,23 +2452,30 @@
 n.state.
+data.
 service
+Id
 );%0A     

Change web UI to match event stream message structure