package com.ruiwenliu.wrapper.presenter;


import com.ruiwenliu.wrapper.base.BaseView;
import com.ruiwenliu.wrapper.http.HttpApi;
import com.ruiwenliu.wrapper.http.OkHttpCreate;

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 retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Amuse
 * Data:2019/1/9 0009
 * Desc:
 */

public abstract class RetrofitPresenter<V extends BaseView> extends WrapperPresenter<V> {

    private int RETRY_COUNT = 0;//请求失败重连次数
    private HttpApi httpApi;
    private Map<Object, DisposableObserver> disMap;


    /**
     * 创建自定义域名服务
     *
     * @param service
     * @param <T>
     * @return
     */
    public <T> T createService(final Class<T> service, String baseUrl) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())//json转换成JavaBean
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(OkHttpCreate.getOkHttpInstance().createOkHttpBuilder().build())
                .build()
                .create(service);
    }

    /**
     * 创建服务
     *
     * @param service
     * @param <T>
     * @return
     */
    public <T> T createApiService(final Class<T> service) {
        return new Retrofit.Builder()
                .baseUrl(getBaseUrl())
                .client(OkHttpCreate.getOkHttpInstance().createOkHttpBuilder().build())
                .addConverterFactory(GsonConverterFactory.create())//json转换成JavaBean
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(service);
    }


    /**
     * 设置订阅 和 所在的线程环境
     */
    public <T> void toSubscribe(Observable<T> observable, DisposableObserver<T> disposableObserver, int position) {
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .retry(RETRY_COUNT)//请求失败重连次数
                .subscribe(disposableObserver);


    }


    /**
     * 获取注解服务
     *
     * @return
     */
    public HttpApi getApi() {
        if (httpApi == null) {
            httpApi = createApiService(HttpApi.class);
        }
        return httpApi;
    }


    /**
     * 设置请求重复次数
     *
     * @return
     */
    public RetrofitPresenter setRetryCount(int count) {
        this.RETRY_COUNT = count;
        return this;
    }


}
