package com.iscs.bozzys.utils.network

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 * 基础请求封装层
 */
object Request {

    // 网络请求的基地址
    private const val BASE_URL = "http://120.27.232.27:9190"

    // 构建请求客户端
    private val okClient = OkHttpClient.Builder()
        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        .sslSocketFactory(getSocketFactory(), createTrustManager())
        .hostnameVerifier { _, _ -> true }
        .build()

    // 构建接口请求工具
    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(okClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build()


    /**
     * 创建一个证书工厂
     */
    private fun getSocketFactory(): SSLSocketFactory {
        // 创建一个不验证证书链的 TrustManager
        val trustAllCerts = arrayOf<TrustManager>(
            object : X509TrustManager {
                override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
                override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
                override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
            }
        )

        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, trustAllCerts, SecureRandom())

        return sslContext.socketFactory
    }

    /**
     * 创建一个不验证证书链的 TrustManager
     */
    private fun createTrustManager(): X509TrustManager {
        val trustAllCerts = arrayOf<TrustManager>(
            object : X509TrustManager {
                override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
                override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
                override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
            }
        )
        return trustAllCerts[0] as X509TrustManager
    }

    fun getRetrofit(): Retrofit {
        return retrofit
    }
}