var AppDispatcher = require('../dispatcher/appDispatcher');
var EventEmitter = require('events').EventEmitter;
var MenuItemCollection = require('../models/menuItemCollection');
var MenuItem = require('../models/menuItem');
var MenuItemConstants = require('../constants/menuItemConstants');
var _ = require('underscore');

var menuItemState = {
  menuItems : [],
  hoveredMenuItem : ''
};


var loadMenuItems = function() { 
  var menuItems = new MenuItemCollection();
  menuItems.fetch({success: function() {
    menuItemState.menuItems = menuItems.models;
    // change will be called automatically when
    // action is run but we need to emit it again
    // when the data arive 
    // it's a bit "unfluxy" but convenient.
    // "true philosophy" would be to run another "data arrived" action
    MenuItemStore.emitChange(); 
  }});
};

var setHovered  = function(id) {
  menuItemState.hoveredMenuItem = id;
}


// Extend MenuItemStore with EventEmitter to add eventing capabilities
var MenuItemStore = _.extend({}, EventEmitter.prototype, {

  // Return Single Item With Details 
  getState: function() {
    return menuItemState;
  },
    // Emit Change event
    emitChange: function() {
      this.emit('change');
    },

    // Add change listener
    addChangeListener: function(callback) {
      this.on('change', callback);
    },

    // Remove change listener
    removeChangeListener: function(callback) {
      this.removeListener('change', callback);
    }
});


// Register callback with AppDispatcher
AppDispatcher.register(function(payload) {
  var action = payload.action;
  var text;

  switch(action.actionType) {

    // Respond to SELECT_ITEM action
    case MenuItemConstants.LOAD_MENU_ITEMS:
      loadMenuItems();
      break;

    case MenuItemConstants.SET_MENU_ITEM_HOVER:
      setHovered(action.menuItem.get('id'));
      break;

    case MenuItemConstants.UNSET_MENU_ITEM_HOVER:
      setHovered('');
      break;
    default:
      return true;
  }

  // If action was responded to, emit change event
  MenuItemStore.emitChange();
  return true;

});

module.exports = MenuItemStore;
