var AppDispatcher = require('../dispatcher/appDispatcher');
var EventEmitter = require('events').EventEmitter;
//var SubCategoryCollection = require('../models/subCategoryCollection');
var SubCategory = require('../models/subCategory');

var NavigationActions = require('../actions/navigationActions');
var BySubCategoryConstants = require('../constants/bySubCategoryConstants');
var ItemCollection = require('../models/itemCollection');
var _ = require('underscore');

var Globals = require('../globals');

var _state = {
    subCategory : (new SubCategory()),
    items: (new ItemCollection()),
    filter: {},
    pagination: {
        offset : 0,
        limit: Globals.DefaultPageSize
    }
};
//var _categoryDetails = new Category();

//var loadSections = function() { 
  //var sections = new SectionCollection();
  //sections.fetch({success: function() {
    //sectionState.sections = sections.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
    //SectionStore.emitChange(); 
  //}});
//};
var fetchItemsBySubCategory = function(subCategoryId, offset, limit, query) {
  //var items = _itemsByCategory;
  query = query || {};
  var items = new ItemCollection();
  items.clearFilter();
  items.setClassificationType(3);
  items.setClassificationId(subCategoryId);
  items.setLimit(limit);
  items.setOffset(offset);

  for(var key in query) {
    if (query.hasOwnProperty(key) && key != 'limit' && key !='offset') {
      items.addFilter(key, query[key]);
    }
  }

  items.fetch({
    success: function(collection, response, options) {
      var total = options.xhr.getResponseHeader('x-total-count');
      items.setTotalCount(total);

      _state.items = items;
      BySubCategoryStore.emitChange();
    }});

};
var load = function(subCategoryId, offset, limit, filter) {

    var subCategory = new SubCategory({id : subCategoryId});
    subCategory.fetch({
        success: function() {
            _state.subCategory = subCategory;
            fetchItemsBySubCategory(subCategoryId, offset, limit, filter);

        }
    });
    _state.filter = filter;
    _state.pagination.limit = limit;
    _state.pagination.offset = offset;
};

var handleFilterCriteriaClick = function(fc, fcv) {
    _state.filter[fc.field_name]  = fcv.filter_value;

    setTimeout(function() {
        NavigationActions.goToSubCategory(_state.subCategory, 0, _state.pagination.limit, _state.filter);
    }, 0);
};

var handleRemoveAppliedFilter= function(name) {
      delete _state.filter[name];

    setTimeout(function() {
        NavigationActions.goToSubCategory(_state.subCategory, 0, _state.pagination.limit, _state.filter);
    }, 0);
};

var handleChangePage = function(page) {
    setTimeout(function() {
        NavigationActions.goToSubCategory(_state.subCategory,  parseInt(page) * _state.pagination.limit, _state.pagination.limit, _state.filter);
    }, 0);
};



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

    getState: function() {
      return _state;
    },
    // 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) {

      case BySubCategoryConstants.LOAD:
          load(action.subCategoryId, action.offset, action.limit, action.filter);
          break;

      case BySubCategoryConstants.FILTER_CRITERIA_CLICK:
          handleFilterCriteriaClick(action.fc, action.fcv);
          break;
      case BySubCategoryConstants.REMOVE_APPLIED_FILTER:
          handleRemoveAppliedFilter(action.name);
          break;
      case BySubCategoryConstants.CHANGE_PAGE:
          handleChangePage(action.page);
          break;

    // Respond to SELECT_ITEM action
    //case SectionConstants.LOAD_SECTIONS:
      //loadSections();      
      //break;

    //case SectionConstants.SET_SECTION_HOVER:
      //setHovered(action.section.get('id'));
      //break;

    //case SectionConstants.UNSET_SECTION_HOVER:
      //setHovered('');
      //break;

    //case CategoryConstants.LOAD_CATEGORY_DETAILS:
      //loadCategoryDetails(action.categoryId);
      //break;

    default:
      return true;
  }

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

});

module.exports = BySubCategoryStore;
