package com.atmob.keyboard_android.http

import com.atmob.keyboard_android.util.LogUtil
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Retrofit网络请求的管理类
 */
object RetrofitManager {
    private fun getOKHttpClient(timeout: Long): OkHttpClient {
        // 日志打印拦截器
        val logInterceptor = HttpLoggingInterceptor {
            LogUtil.d("HttpLoggingInterceptor $it")
        }.setLevel(HttpLoggingInterceptor.Level.BODY)

        val interceptors: MutableList<Interceptor> = ArrayList()

        // 添加自定义拦截器

        val builder = OkHttpClient().newBuilder()
            .callTimeout(timeout, TimeUnit.SECONDS)
            .connectTimeout(timeout, TimeUnit.SECONDS)
            .readTimeout(timeout, TimeUnit.SECONDS)
            .writeTimeout(timeout, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .followRedirects(false)
            .addInterceptor(logInterceptor)

        // 添加拦截器
        builder.interceptors().addAll(interceptors)

        return builder.build()
    }

    private fun getRetrofit(timeout: Long): Retrofit {
        return Retrofit.Builder()
            .client(getOKHttpClient(timeout))
            .baseUrl("apiUrl")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun <T> getService(service: Class<T>, timeout: Long = 10): T {
        return getRetrofit(timeout).create(service)
    }
}