package com.zxhl.cms.net

import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.net.api.ICfgInfoApi
import com.zxhl.cms.utils.PhoneUtils
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Created by gaoleichao on 2018/5/2.
 */
object  EventApiClient {

    private val logInterceptor = HttpLoggingInterceptor()
    private val paramsInterceptor = Interceptor { chain ->
        val request = chain.request()
        val builder = request.url().newBuilder()
        val params = PhoneUtils.addCommonParam()
        val putkeys = params.keys
        for (s in putkeys) {
            builder.addQueryParameter(s, params[s])
        }
        chain.proceed(request.newBuilder().url(builder.build()).build())
    }

    private val headInterceptor = Interceptor { chain ->
        val request = chain.request()
        val builder = request.newBuilder()
//        PhoneUtils.addHeader(builder)
        builder.addHeader(Constant.Device.aid, SettingPreference.getAndroidId())
        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 =  HttpLoggingInterceptor.Level.NONE
        })
        .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_URL)
        .build()

    val cfgApi by lazy { retrofit.create(ICfgInfoApi::class.java) }

}