package com.cake.draw.painting.environment.hy

import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import java.util.concurrent.TimeUnit

class HttpInfoUtil {
    private var mOkHttpClient: OkHttpClient? = null

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

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

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

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

    init {
        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
        mOkHttpClient = builder.build()
    }

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

    @Throws(IOException::class)
    fun postInfo(url: String, json: String, callback: Callback) {
        val requestBody = json.toRequestBody(mediaType)
        val request: Request = Request.Builder()
            .url(url)
            .post(requestBody)
            .build()
        doAsync(request, callback)
    }

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