package cn.com.qmth.stmms.common.utils;

import java.util.LinkedList;
import java.util.List;

public class Paginator {

    /** 滑动窗口默认的大小(7)。 */
    public static final int DEFAULT_SLIDER_SIZE = 7;

    /** 滑动每页显示数量(10)。 */
    public static final int DEFAULT_PAGE_SIZE = 10;

    private int totalCount;

    private int pageNo;

    private int totalPage;

    private int pageSize;

    private int previousPage;

    private int nextPage;

    private List<Integer> slide = new LinkedList<Integer>();

    public Paginator(int pageNo, int totalCount) {
        this.pageNo = pageNo;
        this.totalCount = totalCount;
        caculate();
    }

    public Paginator(int pageNo, int pageSize, int totalCount) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.totalCount = totalCount;
        caculate();
    }

    private void caculate() {
        if (pageSize < 1) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        if (pageNo > 0 && totalCount > 0) {
            totalPage = totalCount / pageSize;
            if (totalCount % pageSize > 0) {
                totalPage++;
            }
            previousPage = pageNo > 1 ? pageNo - 1 : 0;
            nextPage = pageNo < totalPage ? pageNo + 1 : 0;

            buildSlide();
        }
    }

    private void buildSlide() {
        slide.clear();

        int halfSize = DEFAULT_SLIDER_SIZE / 2;
        int start = Math.max(pageNo - halfSize, 1);
        int end = Math.min(start + DEFAULT_SLIDER_SIZE - 1, totalPage);
        for (int i = start; i <= end; i++) {
            slide.add(i);
        }
    }

    public int getTotalCount() {
        return totalCount;
    }

    public int getPageNo() {
        return pageNo;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getPreviousPage() {
        return previousPage;
    }

    public int getNextPage() {
        return nextPage;
    }

    public List<Integer> getSlide() {
        return slide;
    }
}
