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 int mPreviousVisibleItem;
    public boolean mIsScrollingDownLock;

    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(() -> {
            try {
                //BaseChatAdapter adapter = (BaseChatAdapter) recyclerView.getAdapter();

                //mVisibleItem -= adapter.getPositionOffsetForIndex(mVisibleItem);


                if(!mLoading && dy <= 0 && ((totalItemCount - visibleItemCount) <= (mVisibleItem + mVisibleThreshold))) {
                    mLoading = onLoad();
                } else if(!mIsScrollingDownLock && !mLoading && dy > 0 && mHasNewerMessages && (mVisibleItem <= (mVisibleThreshold / 5))) {
                    // TODO: maybe remove after structural changes to the messages list
//                    mPreviousVisibleItem = mVisibleItem + adapter.getPositionOffsetForIndex(mVisibleItem);
//                    mIsScrollingDownLock = true;
                    // TODO -----------------------------------------------------------

                    mLoading = onLoad();
                }
            } catch(Exception e) {
                BeyondSoftLog.logScrollingEvent_E(e.getMessage(), e);
                e.printStackTrace();
            }
        });
    }

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

    public int getVisibleItem() {
        return mVisibleItem;
    }
}