var AppDispatcher = require('../dispatcher/appDispatcher');
var EventEmitter = require('events').EventEmitter;

var SearchConstants = require('../constants/searchConstants');
var SearchActions = require('../actions/searchActions');
var NavigationActions = require('../actions/navigationActions');

var ItemSearchCollection = require('../models/itemSearchCollection');
var globals = require('../globals');
var _ = require('underscore');

var _searchBoxState = {
    q: ''
};

var _searchResultsState = {
    q: '',
    items: (new ItemSearchCollection())
};

var handleSearchBoxChange = function(q) {
    _searchBoxState.q = q;
};


var handleGetSearchResults = function(q) {
    _searchResultsState.q = q;
    _searchBoxState.q = '';

    var searchResults = new ItemSearchCollection();
    searchResults.setQuery(q);
    searchResults.fetch({success: function() {
        _searchResultsState.items = searchResults;
        SearchStore.emit('change');
    }});
};

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

    getSearchBoxState: function() {
        return _searchBoxState;
    },
    getSearchResultsState: function() {
        return _searchResultsState;
    },
  // 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
SearchStore.dispatchToken = AppDispatcher.register(function(payload) {
  var action = payload.action;

  switch(action.actionType) {
    case SearchConstants.SEARCH_BOX_CHANGE:
      handleSearchBoxChange(action.q);
      break;

    case SearchConstants.GET_SEARCH_RESULTS:
      handleGetSearchResults(action.q);
      break;
    default:
      return true;
  }

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

});

module.exports = SearchStore;
