package com.common.commonlib.net

import com.common.commonlib.net.interceptor.BaseUrlInterceptor
import com.common.commonlib.utils.BaseUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 网络请求管理器
 *
 * @author wangym
 * @since 2021/7/28
 */
object RequestManager {
    /**
     * 默认超时时间(s)
     */
    private const val defaultTimeOut: Long = 5

    /**
     * 默认读取超时时间(s)
     */
    private const val defaultReadTimeOut: Long = 10

    private var mRetrofit: Retrofit? = null

    private var mRetrofitWithIntercept: Retrofit? = null

    /**
     * 创建service
     */
    fun <T> create(service: Class<T>): T {
        if (mRetrofit == null) {
            init(null)
        }
        return mRetrofit!!.create(service)
    }

    /**
     * 携带commonInterceptor
     */
    fun <T> create(service: Class<T>, interceptors: List<Interceptor>): T {
        init(interceptors)
        return mRetrofitWithIntercept!!.create(service)
    }

    private fun init(interceptors: List<Interceptor>?) {
        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
        builder.connectTimeout(defaultTimeOut, TimeUnit.SECONDS)
        builder.readTimeout(defaultReadTimeOut, TimeUnit.SECONDS)
        // 动态HOST替换拦截器
        builder.addInterceptor(BaseUrlInterceptor())

        if (!BaseUtils.isListEmpty(interceptors)) {
            for (intercept in interceptors!!) {
                builder.addInterceptor(intercept)
            }
            mRetrofitWithIntercept = Retrofit.Builder()
                .client(builder.build())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("https://www")
                .build()
        } else {
            mRetrofit = Retrofit.Builder()
                .client(builder.build())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("https://www")
                .build()
        }
    }
}