package com.sheep.gamegroup.absBase;

import com.alibaba.fastjson.JSONObject;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.view.fragment.BaseListFragment6;

import java.util.ArrayList;
import java.util.List;

import static com.sheep.gamegroup.util.DataUtil.PER_PAGE;

/**
 * Created by realicing on 2018/11/30.
 * realicing@sina.com
 */
public abstract class AbsApiRefresh<T> implements IApiRefresh {

    public AbsApiRefresh(BaseListFragment6 baseListFragment6) {
        this.baseListFragment6 = baseListFragment6;
    }

    protected List<T> list = new ArrayList<>();
    private BaseListFragment6 baseListFragment6;
    protected int page = 1;
    protected int per_page = PER_PAGE;
    private boolean loadMore = false;

    @Override
    public void setLoadMore(boolean loadMore) {
        this.loadMore = loadMore;
    }

    //还有数据没有获取
    protected boolean hasMore() {
        return ListUtil.size(list) >= per_page * page;
    }

    protected void loadList(List<T> newList) {
        LogUtil.println(AbsApiRefresh.class.getSimpleName(), "loadList", JSONObject.toJSONString(newList));
        list.addAll(newList);
        notifyDataSetChanged();
    }

    private void notifyDataSetChanged() {
        if (baseListFragment6 != null)
            baseListFragment6.notifyDataSetChanged(page, hasMore());
    }

    @Override
    public void clear() {
        list.clear();
        page = 1;
    }

    @Override
    public void loadMoreData() {
        if (!loadMore) {
            loadMore = true;
            if (hasMore()) {
                page += 1;
                LogUtil.println(AbsApiRefresh.class.getSimpleName(), "loadMoreData", "hasMore", page);
                initData();
            } else {
                LogUtil.println(AbsApiRefresh.class.getSimpleName(), "loadMoreData", "noMore", page);
                notifyDataSetChanged();
            }
        }
    }

    @Override
    public List<T> getList() {
        return list;
    }
}
