import { EventEmitter } from 'events';
import dispatcher from '../dispatcher/dispatcher';

const CHANGE_EVENT = 'change';
const state = {
  user:{},
  recentTracks: {},
  topArtists: {}
};

class Store extends EventEmitter {
  emitChange() {
    this.emit(CHANGE_EVENT);
  }

  addChangeListener(callback) {
    this.on(CHANGE_EVENT, callback);
  }

  removeChangeListener(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }

  getState() {
    return state;
  }
}

const store = new Store({
  user:{},
  recentTracks: {},
  topArtists: {}
});

export default store;

export function handleUserRetrieved(state, action) {
  if (!action.user) {
    throw new Error('No user');
  }

  state.user = action.user;
  store.emitChange();
  return state;
}

// it('should add the user to the state', function() {
//   var newState = handleUserRetrieved({}, { user: whatever });
//
//   expect(newState.user)
//     .toBe(whatever)
// })

// var handlers = {
//   userRetrieved: function(state, action) {
//     if (!action.user) {
//       throw new Error('No user');
//     }
//
//     state.user = action.user;
//     store.emitChange();
//     return state;
//   },
//
//   recentTracksRetreived: function(state, action) {
//
//   }
// }

dispatcher.register((action) => {

  // handles[action.type](state, action);

  switch (action.type) {
    case 'userRetrieved':
      handleUserRetrieved(state, action);
      break;

    case 'recentTracksRetreived':
      state.recentTracks = action.recentTracks;
      store.emitChange();
      break;

    case 'topArtistsRetreived':
      state.topArtists = action.topArtists;
      store.emitChange();
      break;

    default:
  }
});

@@ -755,16 +755,439 @@
 ate;%0A%7D%0A%0A
+export function recentTracksRetreived(state, action) %7B%0A  if (!action.recentTracks) %7B%0A    throw new Error('No recent tracks');%0A  %7D%0A%0A  state.recentTracks = action.recentTracks;%0A  store.emitChange();%0A  return state;%0A%7D%0A%0A%0Aexport function topArtistsRetreived(state, action) %7B%0A  if (!action.topArtists) %7B%0A    throw new Error('No top artists');%0A  %7D%0A%0A  state.topArtists = action.topArtists;%0A  store.emitChange();%0A  return state;%0A%7D%0A%0A
 // it('s
@@ -1887,22 +1887,16 @@
 :%0A      
-state.
 recentTr
@@ -1903,55 +1903,31 @@
 acks
- = action.recentTracks;%0A      store.emitChange(
+Retreived(state, action
 );%0A 
@@ -1977,22 +1977,16 @@
 :%0A      
-state.
 topArtis
@@ -1991,53 +1991,31 @@
 ists
- = action.topArtists;%0A      store.emitChange(
+Retreived(state, action
 );%0A 

Move actions denial from the switch case to dedicated function