package com.rv.version;

import android.os.Handler;
import android.os.Looper;

import java.util.ArrayList;
import java.util.List;

public class DownListenerManager {

    private static DownListenerManager instance = null;

    private boolean isDown = false;   // 是否正在下载

    private List<DownListener> listeners;

    private int progress = 0;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    private DownListenerManager() {
        listeners = new ArrayList<>();
    }

    public static DownListenerManager getInstance() {
        if (instance == null) {
            instance = new DownListenerManager();
        }
        return instance;
    }

    public boolean isDown() {
        return isDown;
    }

    public void setDown(boolean down) {
        isDown = down;
    }

    public int getProgress() {
        return progress;
    }

    public void setProgress(int progress) {
        this.progress = progress;
    }

    public void addDownListener(DownListener listener) {
        listeners.add(listener);
    }

    public void removeDownListener(DownListener listener) {
        listeners.remove(listener);
    }


    public void notifyPendChange() {

        setProgress(progress);
        if (listeners.size() <= 0) {
            return;
        }
        mHandler.post(() -> {
            for (DownListener listener : listeners) {
                listener.pending();
            }
        });
    }

    public void notifyProgressChange(final int progress) {

        setProgress(progress);
        if (listeners.size() <= 0) {
            return;
        }
        mHandler.post(() -> {
            for (DownListener listener : listeners) {
                listener.progress(progress);
            }
        });
    }

    public void notifyCompletedChange() {
        if (listeners.size() <= 0) {
            return;
        }
        mHandler.post(() -> {
            for (DownListener listener : listeners) {
                listener.completed();
            }
        });
    }

    public void notifyPausedChange() {
        if (listeners.size() <= 0) {
            return;
        }
        mHandler.post(() -> {
            for (DownListener listener : listeners) {
                listener.paused();
            }
        });
    }

    public void notifyErrorChange() {
        if (listeners.size() <= 0) {
            return;
        }
        mHandler.post(() -> {
            for (DownListener listener : listeners) {
                listener.error();
            }
        });
    }

    public interface DownListener {

        void pending();

        void paused();

        void progress(int progress);

        void completed();

        void error();
    }


}
