package com.ycgis.macall.personalcenter.p.request;


import com.ycgis.macall.personalcenter.p.callback.RequestCallback;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * 负责 请求时activity退出 取消请求
 */
public class CommonCompositeManage {
    private static CommonCompositeManage commonCompositeManage;
    //用于存放 请求的
    private Map<String, CompositeDisposable> manage;

    private CommonCompositeManage(){
        manage = new HashMap<>();
    }

    public synchronized static CommonCompositeManage getInstance(){
        if (commonCompositeManage == null){
            synchronized (CommonCompositeManage.class){
                if (commonCompositeManage == null)
                    commonCompositeManage = new CommonCompositeManage();
            }
        }
        return commonCompositeManage;
    }

    //添加一个请求

    /**
     * 添加一个请求
     * 该方法会在请求发起的时候自动调用 {@link ApiModel#requestRetry(String, Observable, RequestCallback)}
     * @param key 请求标识
     * @param disposable 请求
     */
    public void addDisposable(String key, Disposable disposable){
        CompositeDisposable compositeDisposable = manage.get(key);
        if (compositeDisposable == null||compositeDisposable.isDisposed()){
            compositeDisposable  = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
        manage.put(key,compositeDisposable);
    }

    /**
     * 取消一个请求 {@link #addDisposable(String, Disposable)} 取消在这里添加的请求
     * 该方法在请求完成后回自动调用 @see{@link ApiModel#request(String, Observable, RequestCallback)}
     * 为了应用安全，应当在 Activity、Fragment 的onDestroy() 方法里主动调用，这样当请求还未完成时 Activity、Fragment 销毁时取消请求
     * @param key 请求标识
     */
    public void unDisposable(String key){
        CompositeDisposable compositeDisposable = manage.get(key);
        if (compositeDisposable != null&&!compositeDisposable.isDisposed()){
            compositeDisposable.dispose();
        }
        manage.remove(key);
    }

    /**
     * 取消所有请求
     * 该发放需要主动调用，建议在 MAIN Activity 的 onDestroy() 方法里调用
     */
    public void destory(){
        if (manage==null) return;
        if (manage.isEmpty()) return;
        Set<String> strings = manage.keySet();
        Iterator<String> iterator = strings.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            CompositeDisposable compositeDisposable = manage.get(next);
            if (compositeDisposable != null&&!compositeDisposable.isDisposed()){
                compositeDisposable.dispose();
            }
        }
        manage.clear();
        manage = null ;
        commonCompositeManage = null;
    }
}
