package com.wasu.frescoimagefetchermodule;

import android.support.v7.widget.RecyclerView;

import com.facebook.drawee.backends.pipeline.Fresco;

/**
 * Created by jeepc on 2016/10/31.
 * 用于Recyclerview滚动时暂停加载图片
 * 使用方法recyclerView.addOnScrollListener();
 */

public class RecyclerPauseOnScrollListener extends RecyclerView.OnScrollListener {

    private final boolean pauseOnScroll;
    private final boolean pauseOnSettling;
    private final RecyclerView.OnScrollListener externalListener;

    public RecyclerPauseOnScrollListener( boolean pauseOnScroll, boolean pauseOnSettling) {
        this(pauseOnScroll, pauseOnSettling, null);
    }

    public RecyclerPauseOnScrollListener(boolean pauseOnScroll, boolean pauseOnSettling,
                                    RecyclerView.OnScrollListener customListener) {
        this.pauseOnScroll = pauseOnScroll;
        this.pauseOnSettling = pauseOnSettling;
        externalListener = customListener;
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        switch (newState) {
            case RecyclerView.SCROLL_STATE_IDLE:
                Fresco.getImagePipeline().resume();
                break;
            case RecyclerView.SCROLL_STATE_DRAGGING:
                if (pauseOnScroll) {
                    Fresco.getImagePipeline().pause();
                }
                break;
            case RecyclerView.SCROLL_STATE_SETTLING:
                if (pauseOnSettling) {
                    Fresco.getImagePipeline().pause();
                }
                break;
        }
        if (externalListener != null) {
            externalListener.onScrollStateChanged(recyclerView, newState);
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        if (externalListener != null) {
            externalListener.onScrolled(recyclerView, dx, dy);
        }
    }
}