package com.android.views.swiperefreshrecyclerview;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;

public abstract class EndlessRecyclerOnScrollListener extends  RecyclerView.OnScrollListener {

    private int previousTotal = 0;
    private boolean loading = true;
    int lastCompletelyVisibleItemPosition, visibleItemCount, totalItemCount;

    private RecyclerView.LayoutManager layoutManager;

    public EndlessRecyclerOnScrollListener(RecyclerView.LayoutManager layoutManager) {
        this.layoutManager = layoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = layoutManager.getItemCount();
        if(layoutManager instanceof LinearLayoutManager){
            lastCompletelyVisibleItemPosition = ((LinearLayoutManager)layoutManager).findLastCompletelyVisibleItemPosition();
        }else if(layoutManager instanceof StaggeredGridLayoutManager){
            int [] positions = ((StaggeredGridLayoutManager)layoutManager).findLastCompletelyVisibleItemPositions(null);
            for(int k = 0; k< positions.length; k++){
                if(lastCompletelyVisibleItemPosition<positions[k]){
                    lastCompletelyVisibleItemPosition = positions[k];
                }
            }
        }
        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading
                && (visibleItemCount > 0)
                && (lastCompletelyVisibleItemPosition >= totalItemCount - 1)) {
            onLoadMore();
            loading = true;
        }
    }

    public void setLoading(boolean loading){
        this.loading = loading;
        if(!loading){
            visibleItemCount = 0;
            lastCompletelyVisibleItemPosition = 0;
            totalItemCount = 0;
            previousTotal = 0;
        }
    }

    public abstract void onLoadMore();
}