package com.zx.ad.modulecommon.net

import android.text.TextUtils
import com.zx.ad.modulecommon.AdConstant
import com.zx.ad.modulecommon.AdNetConfig
import com.zx.ad.modulecommon.AdPhoneUtil
import com.zx.ad.modulecommon.net.api.IAdApi
import okhttp3.Interceptor
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object ZXADClient {

    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 {
            AdPhoneUtil.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(AdConstant.Device.aid, AdConstant.param.androidId)
        builder.addHeader(AdConstant.Device.env, AdConstant.param.env)
        if (!TextUtils.isEmpty(AdConstant.param.userAgent)) {
            builder.addHeader("web-user-agent", AdConstant.param.userAgent)
            builder.removeHeader("User-Agent")
            builder.addHeader("User-Agent", AdConstant.param.userAgent)
        }
        chain.proceed(builder.build())
    }

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

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

    val adApi by lazy { retrofit.create(IAdApi::class.java) }
}