package ch.hearc.jeef.util;

import java.util.ArrayList;
import java.util.List;
import javax.faces.model.DataModel;

public abstract class PaginationHelper {

    private int pageSize;
    private int page;

    public PaginationHelper(int pageSize) {
        this.pageSize = pageSize;
    }

    public abstract int getItemsCount();

    public abstract DataModel createPageDataModel();

    public int getPageFirstItem() {
        return page * pageSize;
    }

    public int getPageLastItem() {
        int i = getPageFirstItem() + pageSize - 1;
        int count = getItemsCount() - 1;
        if (i > count) {
            i = count;
        }
        if (i < 0) {
            i = 0;
        }
        return i;
    }

    public boolean isHasNextPage() {
        return (page + 1) * pageSize + 1 <= getItemsCount();
    }

    public void nextPage() {
        if (isHasNextPage()) {
            page++;
        }
    }

    public void setPage(int page) {
        this.page = page - 1;
    }

    public boolean isHasPreviousPage() {
        return page > 0;
    }

    public void previousPage() {
        if (isHasPreviousPage()) {
            page--;
        }
    }

    public void lastPage() {
        page = getNumberPages() - 1;
    }

    public int getNumberPages() {
        return (int) Math.ceil(getItemsCount() / (double) getPageSize());
    }

    public int getPageSize() {
        return pageSize;
    }

    public List<Integer> getPreviousPages() {
        List<Integer> pages = new ArrayList<>();
        for (int i = 0, j = 0; i < page && j < 5; ++i, ++j) {
            pages.add(i + 1);
        }
        return pages;
    }

    public int getCurrentPage() {
        return page + 1;
    }

    public List<Integer> getNextPages() {
        List<Integer> pages = new ArrayList<>();
        for (int i = page + 1, j = 0; i < getNumberPages() && j < 5; ++i, ++j) {
            pages.add(i + 1);
        }
        return pages;
    }
}

@@ -433,20 +433,25 @@
  return 
-p
+getP
 age
+()
  * pageS
@@ -775,20 +775,25 @@
 return (
-p
+getP
 age
+()
  + 1) * 
@@ -977,28 +977,282 @@
     
-this.page = page - 1
+page--;%0A        if (page %3E getNumberPages() - 1) %7B%0A            lastPage();%0A        %7D else if (page %3C 0) %7B%0A            this.page = 0;%0A        %7D else %7B%0A            this.page = page;%0A        %7D%0A    %7D%0A    %0A    public int getPage() %7B%0A        setPage(page + 1);%0A        return page
 ;%0A  
@@ -1312,20 +1312,25 @@
  return 
-p
+getP
 age
+()
  %3E 0;%0A  
@@ -1820,20 +1820,25 @@
  0; i %3C 
-p
+getP
 age
+()
  && j %3C 
@@ -1970,20 +1970,25 @@
  return 
-p
+getP
 age
+()
  + 1;%0A  
@@ -2104,20 +2104,25 @@
 int i = 
-p
+getP
 age
+()
  + 1, j 

Fix pagination error