package com.rc.httpcore

import android.content.Context
import android.util.Log
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.rc.httpcore.client.factory.ClientFactory
import com.rc.httpcore.client.factory.RetrofitFactory
import com.rc.httpcore.config.OkHttpDNS
import com.rc.httpcore.converter.NullOnEmptyConverterFactory
import com.rc.httpcore.interceptor.TokenHeaderInterceptor
import com.rc.httpcore.vo.LogInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import java.util.logging.Level
import java.util.logging.Logger

object HttpClient {

    //    private const val TIMEOUT_DEFAULT = 3 * 60L
    private const val TIMEOUT_DEFAULT = 10L

    private var mAppContext: Context? = null
    private val LOGGER: Logger = Logger.getLogger(HttpClient::class.java.name)
    var token: String? = null
    var vName: String = "1.0.0"


    fun init(appContext: Context) {
        this.mAppContext = appContext
    }

    fun getAppContext() = mAppContext

    fun createClientFactory(): ClientFactory {
        return when (HttpConfig.HTTP_STRATEGY_Retrofit) {
            HttpConfig.HTTP_STRATEGY -> RetrofitFactory()
            else -> RetrofitFactory()
        }
    }

    fun <T> createRetrofitApi(
        apiClass: Class<T>,
        baseUrl: String = HttpConfig.API_BASE_URL,
    ): T {
        return buildRetrofit(baseUrl).create(apiClass)
    }

    private fun buildRetrofit(
        baseUrl: String = HttpConfig.API_BASE_URL,
        okHttpClient: OkHttpClient = buildHttpClient()
    ): Retrofit {
        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(baseUrl)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(NullOnEmptyConverterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    private fun buildHttpClient(): OkHttpClient {
//        //设置日志打印级别
//        val interceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
//            LOGGER.log(Level.INFO, message)
//        })
//        interceptor.level = HttpLoggingInterceptor.Level.BODY
        return return OkHttpClient.Builder()
            .readTimeout(TIMEOUT_DEFAULT, TimeUnit.SECONDS) // 设置读取超时时间
            .connectTimeout(TIMEOUT_DEFAULT, TimeUnit.SECONDS) // 设置请求超时时间
            .writeTimeout(TIMEOUT_DEFAULT, TimeUnit.SECONDS) // 设置写入超时时间
            .addNetworkInterceptor(TokenHeaderInterceptor())
            .addInterceptor(LogInterceptor())//添加请求日志
//            .retryOnConnectionFailure(true) // 设置出现错误进行重新连接
//            .dns(OkHttpDNS())
            .build()
    }

}