package com.joyful.euphoria.board.environment

import android.content.Context
import android.net.ConnectivityManager
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

class VmHttpUtil {

    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetworkInfo = connectivityManager?.activeNetworkInfo
        return activeNetworkInfo != null && activeNetworkInfo.isConnected
    }

    private var mOkHttpClient: OkHttpClient? = null

    companion object {
        val mInstance: VmHttpUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            VmHttpUtil()
        }
    }

    private val CONNECT_TIMEOUT: Long = 60 //超时时间，秒

    private val READ_TIMEOUT: Long = 60 //读取时间，秒

    private val WRITE_TIMEOUT: Long = 60 //写入时间，秒

    init {
        // ---- 不安全：信任所有证书（仅测试用） ----
        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("TLS")
        sslContext.init(null, trustAllCerts, SecureRandom())
        val sslSocketFactory = sslContext.socketFactory

        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
        mOkHttpClient = builder.build()
    }

    private val mediaType = "application/json; charset=utf-8".toMediaType()

    fun getIPInfo(url: String, callback: Callback) {
        val request: Request = Request.Builder()
            .url(url)
            .get()
            .build()
        doAsync(request, callback)
    }

    /**
     * 异步请求
     */
    @Throws(IOException::class)
    private fun doAsync(request: Request, callback: Callback) {
        //创建请求会话
        val call = mOkHttpClient!!.newCall(request)
        //同步执行会话请求
        call.enqueue(callback)
    }
}