package com.mjsheng.myappstore.listener;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;


public class AutoLoadListener extends RecyclerView.OnScrollListener {

    public interface AutoLoadCallBack {
        void execute();

        void stopLoad();

        void startLoad();
    }

    private AutoLoadCallBack mCallback;

    public AutoLoadListener(AutoLoadCallBack callback) {
        this.mCallback = callback;
    }

    private boolean isSlidingUpward = true;
    private boolean isFirst = true;

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();

        switch (newState) {
            case RecyclerView.SCROLL_STATE_DRAGGING:
            case RecyclerView.SCROLL_STATE_SETTLING:
                // 当ListView处于滑动状态时，停止加载图片，保证操作界面流畅
                mCallback.stopLoad();
                break;
            case RecyclerView.SCROLL_STATE_IDLE:
                // 当ListView处于静止状态时，继续加载图片
                mCallback.startLoad();

                int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
                int itemCount = manager.getItemCount();

                if (lastItemPosition == (itemCount - 1) && !recyclerView.canScrollVertically(1) && isFirst) {
                    Toast.makeText(recyclerView.getContext(), "已经拖动至底部，再次拖动即可翻页", Toast.LENGTH_SHORT).show();
                    isFirst = false;
                } else if (lastItemPosition == (itemCount - 1) && !recyclerView.canScrollVertically(1) && !isFirst) {
                    mCallback.execute();

                }
                break;
        }
    }

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

    }

}