package com.ym.library.net

import android.text.TextUtils
import com.ym.library.BuildConfig
import com.ym.library.Constant
import com.ym.modulecommon.net.NetConfig
import com.ym.modulecommon.utils.PhoneUtils
import com.ym.modulecommon.utils.SettingPreference
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @author (wangXuewei)
 * @datetime 2020-10-09 22:20 GMT+8
 * @detail :
 */
object GameApiClient {

    private val logInterceptor = HttpLoggingInterceptor()
    private val paramsInterceptor = Interceptor { chain ->
        val request = chain.request()
        val builder = request.url().newBuilder()

        if (request.url().toString().contains("yilan")) {
            chain.proceed(request.newBuilder().build())
        } else {
            PhoneUtils.addParam(request, builder)
            chain.proceed(request.newBuilder().url(builder.build()).build())
        }
    }

    private val headInterceptor = Interceptor { chain ->
        val request = chain.request()
        val builder = request.newBuilder()
        builder.addHeader(Constant.aid, SettingPreference.getAndroidId())
        builder.addHeader(Constant.Device.env, Constant.Param.env)
        if (!TextUtils.isEmpty(SettingPreference.getUserAgent())) {
            builder.addHeader("web-user-agent", SettingPreference.getUserAgent())
            builder.removeHeader("User-Agent")
            builder.addHeader("User-Agent", SettingPreference.getUserAgent())
        }
        val headers: Request = builder.build()
        chain.proceed(headers)
    }

    private val httpClient = okhttp3.OkHttpClient.Builder()
        .connectTimeout(10000, TimeUnit.MILLISECONDS)
        .readTimeout(10000, TimeUnit.MILLISECONDS)
        .addInterceptor(logInterceptor.apply {
            level =  if(BuildConfig.DEBUG)HttpLoggingInterceptor.Level.BODY else{HttpLoggingInterceptor.Level.NONE}
        })
//        .retryOnConnectionFailure(false)
        .hostnameVerifier { hostname, session ->
            true
        }
        .addInterceptor(paramsInterceptor)
        .addInterceptor(headInterceptor)
        .build()!!

    private val retrofit = retrofit2.Retrofit.Builder()
        .client(httpClient)
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(NetConfig.BASE_FEED_URL)
        .build()

    val gameApi by lazy { retrofit.create(IGameApi::class.java) }

}