package com.baoshi.swms.net.subscribe;

import com.baoshi.swms.App;
import com.baoshi.swms.net.build.NetBuilder;
import com.baoshi.swms.net.constant.WasConstant;
import com.baoshi.swms.net.interceptor.CacheInterceptor;
import com.baoshi.swms.net.interceptor.HeaderInterceptor;

import java.io.File;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.ResponseBody;

/**
 * 基础全局网络订阅者
 *
 * @author Zhendong Zhou
 * @date 2021/12/21 15:43
 */
public class BaseSubscribe {
    /**
     * 关键方法，可以根据需求产出不同的api
     * @param baseUrl
     * @param params
     * @param apiClass
     * @param <T>
     * @return
     */
    public static <T>T newApi(String baseUrl, Map<String, String> params, Class<T> apiClass) {
        NetBuilder builder = new NetBuilder()
                .setConnectTimeout(WasConstant.DEFAULT_CONNECT_TIMEOUT)
                .setReadTimeout(WasConstant.DEFAULT_READ_TIMEOUT)
                .setWriteTimeout(WasConstant.DEFAULT_WRITE_TIMEOUT)
                .setRetryOnConnectionFailure(true);
        //添加header
        if (params != null && params.size()>0) {
            HeaderInterceptor headerInterceptor = new HeaderInterceptor(params);
            builder.addInterceptor(headerInterceptor);
        }
        //添加缓存
        File cacheFile = new File(App.getAppContext().getExternalCacheDir(), WasConstant.CACHE_NAME);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        builder.addCache(cache);

        //添加缓存拦截器
        CacheInterceptor cacheInterceptor = new CacheInterceptor(App.getAppContext());
        builder.addInterceptor(cacheInterceptor);

        return builder.build(baseUrl).create(apiClass);
    }

    /**
     * 设置订阅 和 所在的线程环境
     * @param o
     * @param s
     */
    public static void toSubscribe(Observable<ResponseBody> o, DisposableObserver<ResponseBody> s) {
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .retry(1)//请求失败重连次数
                .subscribe(s);
    }

    protected static Map<String, String> getHeaderParams() {
        return null;
    }
}
