var React = require('react');
var SingleItem = require('./singleItem');
var ItemCollection = require('../../models/itemCollection.js');

var ItemList = React.createClass({
    changePage: function(page, e) {
      e.preventDefault();
      if(this.props.onPageChange) {
        this.props.onPageChange(page);
      }
    },
    render: function() {

        var items = this.props.items.models.map( function(item) {
            return  (
                 <SingleItem item={item} key={item.id}/>
                 );
        });

        return (
            <div className="row-fluid">
            <div className="span10">
             <div style={{marginTop: 35, padding: '0 25px'}} className="row">
               {items}
            </div>
            {this.getPages()}
            </div>
            </div>
        );
    },
      getPages: function() {
        if (!this.props.paginationEnabled) {
          return "";
        }

        var nrOfPages = Math.ceil(this.props.total/ this.props.limit);
        if (nrOfPages === 1) {
          return "";
        }

        var maxSlots = 10;
        var selectedIndex = Math.floor(this.props.currentOffset / this.props.limit);

        var start, end;
        start = selectedIndex - Math.floor(maxSlots / 2);
        end = selectedIndex + Math.floor(maxSlots / 2 ) + 1;

        if (start < 0) start = 0;
        if (end > nrOfPages) end = nrOfPages;

        if ((end - start) < maxSlots) {
          start = Math.max(0, end - maxSlots);
          end = Math.min(nrOfPages, start + maxSlots);
        }

        var pages = [];
        for(var i = start; i < end; i++) {
          var cn = i === selectedIndex ? "active": "";
          pages.push(<li className={cn}><a  onClick={this.changePage.bind(this, i)}href="#">{i + 1}</a></li>)
        }

        return (
            <nav>

            <ul className="pagination">
            {pages}
            </ul>
            </nav>)
      }

});


module.exports = ItemList;
