package com.lukouguoji.module_base.http.net

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.lukouguoji.module_base.http.net.Api
import com.lukouguoji.module_base.http.user.SelfLoginInterceptor
import com.lukouguoji.module_base.impl.HttpLogImpl
import dev.utils.DevFinal
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import kotlin.properties.Delegates

/**
 * @author ：Martin
 * @data : 2018/6/21 15:39
 */
object NetApply {

    // 超时时间
    private const val DEFAULT_TIMEOUT: Long = 30000L

    //  接口对象
    var api: Api by Delegates.notNull()

    // JSON解析器
    val gson: Gson = GsonBuilder()
        // 设置日期格式
        .setDateFormat(DevFinal.TIME.yyyyMMddHHmmss_HYPHEN)
        .registerTypeAdapterFactory(NullStringAdapterFactory())
        // 序列化null
        .serializeNulls()
        .create()

    init {
        init()
    }

    fun init() {
        // 初始化日志拦截器
        val logInterceptor = HttpLoggingInterceptor(HttpLogImpl())
        // 设置日志拦截器的日志级别
        logInterceptor.level =
            HttpLoggingInterceptor.Level.BODY

        // 初始化OkHttp
        val client = OkHttpClient.Builder()
            .addInterceptor(SelfLoginInterceptor)
            // 添加日志拦截器
            .addInterceptor(logInterceptor)
            // 连接超时时间
            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
            // 读取超时时间
            .readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
            // 写入超时时间
            .callTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
            .build()

        // 初始化Retrofit
        val retrofit = Retrofit.Builder()
            // 设置OkHttp
            .client(client)
            // 设置网络请求的Url地址
            .baseUrl(Api.BASE_URL)
            // 添加Gson解析器
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()

        api = retrofit.create(Api::class.java)

        println("----------------------------------------------")
        println("init.api:"+ api.toString())
        println("init.Api:"+ Api.BASE_URL)
    }

}