package com.cheng.blzb.net

import com.cheng.blzb.BuildConfig
import com.cheng.blzb.common.Constants
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 * 网络请求方法 结合了rxJava
 */
class HttpRetrofit internal constructor() {
    companion object {
        private const val DEFAULT_TIMEOUT = 20L
    }

    val apiService: ApiService

    init {
        //手动创建一个OkHttpClient并设置超时时间
        val httpClient = OkHttpClient.Builder()
        httpClient.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
        //header拦截
        httpClient.addInterceptor(RequestHeaderInterceptor())
        httpClient.addInterceptor(ContentTypeInterceptor())
        //请求拦截
        httpClient.addInterceptor(RequestInterceptor())
        //响应拦截
        httpClient.addInterceptor(ResponseInterceptor())


        val gson = GsonBuilder().setLenient().registerTypeAdapterFactory(MyTypeAdapterFactory()).create()
        val retrofit = Retrofit.Builder()
            .client(httpClient.build())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(if (BuildConfig.DEBUG) Constants.TestUrl else Constants.BaseUrl)
            .build()

        apiService = retrofit.create(ApiService::class.java)
    }


}
