package com.zxhl.cms.net

import com.zxhl.cms.utils.PhoneUtils
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.net.api.*
import com.zxhl.cms.utils.GsonInstance
import okhttp3.Interceptor
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 ApiClient {

    private val logInterceptor = HttpLoggingInterceptor()
    private val paramsInterceptor = Interceptor { chain ->
        val request = chain.request()
        val builder = request.url.newBuilder()
        if (request.url.host.toString().contains("zhangxinhulian.com")) {
            val builder = request.url.newBuilder()
            PhoneUtils.addParam(request, builder)
            chain.proceed(request.newBuilder().url(builder.build()).build())
        } else {
            chain.proceed(request.newBuilder().build())
        }
    }

    private val headInterceptor = Interceptor { chain ->
        val request = chain.request()
        val builder = request.newBuilder()
        if (request.url.host.toString().contains("zhangxinhulian.com")) {
            PhoneUtils.addHeader(builder)
        }
        chain.proceed(builder.build())
    }

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

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

    val videoInfoApi by lazy { retrofit.create(IVideoInfoApi::class.java) }
    val userInfoAPi by lazy { retrofit.create(IUserInfoApi::class.java) }
    val cfgInfoAPi by lazy { retrofit.create(ICfgInfoApi::class.java) }
    val adApi by lazy { retrofit.create(IAdApi::class.java) }
    val homeApi by lazy { retrofit.create(IHomeApi::class.java) }
    val shopApi by lazy { retrofit.create(IShopApi::class.java) }
}