var React = require('react'),
Router = require('react-router'),
Category = require('../../models/category'),
SubCategory = require('../../models/subCategory'),
Section = require('../../models/section'),
ItemCollection = require('../../models/itemCollection'),
ItemActions = require('../../actions/itemActions.js'),
CategoryActions = require('../../actions/categoryActions.js'),
CategoryStore = require('../../stores/categoryStore'),
ItemStore = require('../../stores/itemStore'),
NavigationStore = require('../../stores/navigationStore'),
ItemList = require('../items/itemList'),
NavigationActions = require('../../actions/navigationActions'),
LinkBanner = require('../linkBanner/linkBanner'),
Globals = require('../../globals');

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

var ByCategory = React.createClass({
  mixins: [Router.State],
  getInitialState: function() {
    var category = new Category();
    var items = new ItemCollection();
    return {
      category: category,
      items: items,
      filter :{},
      pagination: {}
    };
  },
  filter: {},
  onFCClick: function(fc, fcv) {
    var q = {};
    q[fc.field_name] = fcv.filter_value;
    var section = new Section(this.state.category.get('section'));
    var category = this.state.category;

    this.filter[fc.field_name] = fcv.filter_value;
    NavigationActions.goToCategory(category, section, this.filter, 0, this.state.pagination.limit);
  },
  removeAppliedFilter: function(name) {
    delete this.filter[name];
    var section = new Section(this.state.category.get('section'));
    var category = this.state.category;
    NavigationActions.goToCategory(category, section, this.filter, 0, this.state.pagination.limit);

  },
  onSCClick: function(sc) {
    var subCategory = new SubCategory(sc);
    NavigationActions.goToSubCategory(subCategory, 0, Globals.defaultLimit);
    event.preventDefault();
  },
  changePage: function(page) {
    var section = new Section(this.state.category.get('section'));
    var category = this.state.category;

    NavigationActions.goToCategory(category, section, this.filter, parseInt(page) * this.state.pagination.limit, this.state.pagination.limit);
  },
  render: function() {
    var self = this;
    return (
      <div>
        <div
          style={{height: "100%"}}
          className="col-lg-2 col-md-2 col-sm-4 col-xs-4 sidebar ">
          <ul>
            {(this.state.category.get('sub_categories') || []).map(function(sc) {
              return (
                <li>
                  <a href="#" onClick={self.onSCClick.bind(self, sc)}>
                    {sc.name}
                  </a>
                </li>
              )
            })}
          </ul>

          <FilterCriteriaSelector
            filterCriterias={this.state.category.get('filter_criterias')}
            onFCClick={this.onFCClick} />

        </div>

        <div
          style={{height: "100%"}}
          className="col-lg-10 col-md-10 col-sm-8 col-xs-8 ">

          <LinkBanner
            locationName="category"
            locationId={Number(this.getParams().id)} />

          <h3> {this.state.category.get('name')}</h3>
        
          <div>
            <AppliedFiltersList
              filters={this.appliedCategoryFiltersArray()}
              onRemove={self.removeAppliedFilter} />

          </div>

          <ItemList
            items={this.state.items}
            paginationEnabled={true}
            total={this.state.items.totalCount}
            limit={this.state.pagination.limit}
            onPageChange={this.changePage}
            currentOffset={this.state.pagination.offset} />
        </div>
      </div>
    );
  },
  appliedCategoryFiltersArray: 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 categoryId = this.getParams().id;

    this.filter = this.getQuery();
    var offset = this.filter.offset || 0;
    var limit = this.filter.limit || Globals.DefaultPageSize;

    this.setState({
      filter: this.filter,
      pagination: {
        offset: offset,
        limit: limit
      }
    });
    ItemActions.loadByCategory(categoryId, offset, limit, this.filter);
    CategoryActions.loadCategoryDetails(categoryId);
  },
  componentWillReceiveProps: function() {
    this.update();
  },
  componentDidMount: function() {
    this.update();

    ItemStore.addChangeListener(this._onChange);
    CategoryStore.addChangeListener(this._onChange);
  },
  componentWillUnmount: function() {
    ItemStore.removeChangeListener(this._onChange);
    CategoryStore.removeChangeListener(this._onChange);
  },
  _onChange: function() {
    if(this.isMounted()) {
      this.setState({
        items: ItemStore.getItemsForCategory(),
        category: CategoryStore.getCategoryDetails()
      });
    }
  }

});

module.exports = ByCategory;
