package com.qmth.boot.tools.iterator;

import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * 适用于分页读取数据对象的迭代器封装
 */
public abstract class PageListIterator<E> implements Iterator<E> {

    private int pageNumber;

    private int pageSize;

    private Deque<E> dataList;

    private boolean finish;

    /**
     * 构造分页迭代器
     *
     * @param pageSize - 每页数据量，应该大于0
     */
    public PageListIterator(int pageSize) {
        if (pageSize <= 0) {
            throw new IllegalArgumentException("Iterator pageSize should greater than 0");
        }
        this.pageNumber = 0;
        this.pageSize = pageSize;
        this.finish = false;
        this.dataList = new LinkedList<>();
    }

    @Override
    public boolean hasNext() {
        if (!finish) {
            if (dataList.isEmpty()) {
                pageNumber++;
                Collection<E> pageList = getPageList(pageNumber, pageSize);
                if (pageList != null) {
                    for (E item : pageList) {
                        dataList.offerLast(item);
                    }
                }
                finish = dataList.isEmpty();
            }
        }
        return !finish;
    }

    @Override
    public E next() {
        return dataList.pollFirst();
    }

    /**
     * 分页获取对象集合，页码从1开始
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public abstract Collection<E> getPageList(int pageNumber, int pageSize);
}
