var React = require('react'),
    Router = require('react-router');

var BySubCategoryActions = require('../../actions/bySubCategoryActions');
var BySubCategoryStore = require('../../stores/bySubCategoryStore');
var ItemStore = require('../../stores/itemStore');
var CategoryStore = require('../../stores/categoryStore');

var Globals = require('../../globals');
var FilterCriteriaSelector = require('./filterCriteriaSelector');
var AppliedFiltersList = require('./appliedFiltersList');

var NavigationActions = require('../../actions/navigationActions');
var ItemList = require('../items/itemList');
var BySubCategory = React.createClass({
    mixins: [Router.State],
    getInitialState : function() {
        return BySubCategoryStore.getState();
    },
    onFCClick: function(fc, fcv) {
        BySubCategoryActions.filterCriteriaClick(fc, fcv);
    },
    removeAppliedFilter: function(name) {
        BySubCategoryActions.removeAppliedFilter(name);
    },
    onChangePage: function(page) {
        BySubCategoryActions.changePage(page);
    },
    render : function() {

        return (<div> 
            <div className='col-md-2'>
                <FilterCriteriaSelector filterCriterias={this.state.subCategory.get('filter_criterias')} onFCClick={this.onFCClick} />
            </div>
            <div classname='col-md-10'>
            
            <h2>
              {this.state.subCategory.get('name')}
            </h2>
   
    <div>
          <AppliedFiltersList filters={this.appliedSubCategoryFiltersArray()} onRemove={this.removeAppliedFilter} />
       
      </div>
        <ItemList items={this.state.items} paginationEnabled={true} total={this.state.items.totalCount} limit={this.state.pagination.limit} onPageChange={this.onChangePage} currentOffset={this.state.pagination.offset} />
            </div>
            </div>)
    },
    appliedSubCategoryFiltersArray: function() {
      var filters = [];
      for(var key in this.state.filter) {
        if(this.state.filter.hasOwnProperty(key) && key !== 'limit' && key !== 'offset') {
          filters.push({name: key, value: this.state.filter[key]});
        }
      }
      return filters;
    },
    update: function() {
      var subCategoryId = this.getParams().id;
      var filter = this.getQuery();
      var offset = filter.offset || 0;
      var limit = filter.limit || Globals.DefaultPageSize;

      BySubCategoryActions.load(subCategoryId, offset, limit, filter);
    },
    componentWillReceiveProps: function() {
      this.update();
    },
    componentDidMount: function() {
      BySubCategoryStore.addChangeListener(this._onChange);
      this.update();
    },
    componentWillUnmount: function() {
      BySubCategoryStore.removeChangeListener(this._onChange);
    },
    _onChange: function() {
      if(this.isMounted()) {
          this.setState(BySubCategoryStore.getState());
      }
    }
});

module.exports = BySubCategory;
