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;
    private boolean mLoading = false;
    private final LinearLayoutManager mLayoutManager;
    private int mVisibleItem;
    protected boolean mHasNewerMessages = false;

    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 - 1) {
                mLoading = false;
                mPreviousTotal = totalItemCount;
            }
        }

        if(recyclerView == null) {
            return;
        }

        BeyondSoftLog.logScrollingEvent_W("Scrolling...");

        recyclerView.post(() -> {
            try {
                if(!mLoading && dy <= 0 && ((totalItemCount - visibleItemCount) <= (mVisibleItem + mVisibleThreshold))) {
                    mLoading = onLoad();
                } else if(!mLoading && dy > 0 && mHasNewerMessages && (mVisibleItem <= mVisibleThreshold)) {
                    mLoading = onLoad();
                }
            } catch(Exception e) {
                BeyondSoftLog.logScrollingEvent_E(e.getMessage(), e);
                e.printStackTrace();
            }
        });
    }

    public abstract boolean onLoad();
}