package com.gingersoft.gsa.cloud.download.mvp.model.downmanager;

import com.gingersoft.gsa.cloud.base.threadPool.ThreadPoolManager;
import com.gingersoft.gsa.cloud.base.utils.okhttpUtils.OkHttp3Utils;
import com.gingersoft.gsa.cloud.download.mvp.presenter.DownloadPresenter;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-02-25
 * 修订历史：2020-02-25
 * 描述：數據下載管理類
 */
public class DownloadManager {


    private static DownloadManager downloadManager;
    //当前请求响应成功数
    private int responseSuccessCount;
    //当前请求响应失敗数
    private int responseErrorCount;
    //当前所需請求數
    private int requestCount;

    public static DownloadManager getInstance() {
        if (downloadManager == null) {
            downloadManager = new DownloadManager();
        }
        return downloadManager;
    }

    public DownloadManager takeRequestExecute(List<DownloadRequest> requests) {
        this.requestCount = requests.size();
        //重置响应数
        this.responseSuccessCount = 0;

        ThreadPoolManager poolManager = ThreadPoolManager.getInstence();

        for (int i = 0; i < requests.size(); i++) {
            DownloadRequest request = requests.get(i);
            if (request != null) {
                DownloadTaskImp taskImp = new DownloadTaskImp(request);
                poolManager.putExecutableTasks(taskImp);
            }
        }
        return this;
    }

    public DownloadManager takeRequestExecute(List<DownloadRequest> requests, OnRunnableListener listener) {
        if (listener == null) {
            return this;
        }

        this.requestCount = requests.size();
        //重置响应数
        this.responseSuccessCount = 0;

        ThreadPoolManager poolManager = ThreadPoolManager.getInstence();

        for (int i = 0; i < requests.size(); i++) {
            DownloadRequest request = requests.get(i);
            if (request != null) {
                poolManager.putExecutableTasks(new Runnable() {
                    @Override
                    public void run() {
                        listener.run(request);
                    }
                });
            }
        }
        return this;
    }


    private OnRunnableListener listener;

    public void setRunnableListener(OnRunnableListener listener) {
        this.listener = listener;
    }

    public interface OnRunnableListener {

        void run(Object o);
    }
}
