var angular = require('angular');
require('../modules');
var module = angular.module('commons.services'),
  nativePush = Array.prototype.push;
  
module.factory('PageableArray', function() {
  function PageableArray(allItems, pageSize) {
    this.pageSize = pageSize || 15;
    this.items = [];
    this.allItems = allItems;
    this.currentPage = 0;
  }

  PageableArray.prototype = {
    /**
     * 重置分页状态
     * 
     * @param  {Array} items
     */
    reset: function(items) {
      /* istanbul ignore else  */
      if (items) {
        this.allItems = items;
      }
      this.items.splice(0, this.items.length);
      this.currentPage = 0;
      return this.loadPage(this.currentPage);
    },

    /**
     * 加载更多的数据
     * @return {Promise}
     */
    loadMore: function() {
      if(this.allItems.length <= this.pageSize * (this.currentPage + 1)) {
        return null;
      } else {
        this.currentPage ++;
        return this.loadPage(this.currentPage);
      }
    },

    /**
     * 加载page页的数据
     * @param  {Number} page
     * @return {Promise}
     */
    loadPage: function(page) {
      var start = page * this.pageSize,
        end = Math.min((page + 1) * this.pageSize, this.allItems.length);
      nativePush.apply(this.items, this.allItems.slice(start, end));
      return this.items;
    }
  };

  return PageableArray;
});
