package de.beyondsoft.ownchat.utils;

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

public abstract class EndlessScrollListener extends RecyclerView.OnScrollListener {

    private int mPreviousTotal = 0;
    private int mVisibleThreshold = 5;
    private boolean mLoading = false;
    private final LinearLayoutManager mLayoutManager;
    private int mVisibleItem;

    public void reset() {
        mPreviousTotal = 0;
    }

    protected EndlessScrollListener(int visibleThreshold, LinearLayoutManager layoutManager) {
        mVisibleThreshold = visibleThreshold;
        mLayoutManager = layoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        int visibleItemCount = mLayoutManager.getChildCount();
        int totalItemCount = mLayoutManager.getItemCount();
        mVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

        if (mLoading) {
            if (totalItemCount > mPreviousTotal) {
                mLoading = false;
                mPreviousTotal = totalItemCount;
            }
        }

        if (recyclerView == null) {
            return;
        }

        recyclerView.post(() -> {
            if (!mLoading && (totalItemCount - visibleItemCount) <= (mVisibleItem + mVisibleThreshold)) {
                mLoading = onLoad();
            }
        });
    }

    /**
     * @return true if loading was started now, false otherwise
     */
    public abstract boolean onLoad();

    public int getVisibleItem() {
        return mVisibleItem;
    }
}