package melody.offline.music.http

import android.content.Context
import android.net.ConnectivityManager
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit

class MyHttpUtil {

    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: MyHttpUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            MyHttpUtil()
        }
    }

    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 postSaveAppData(json: JSONObject, callback: Callback) {
        val query: HashMap<String, String> = HashMap()
        val body = BaseApiUtil.shared.initPostBody(
            "POST",
            BaseApiUtil.getAppDataURL,
            query,
            json
        )
        val path = BaseApiUtil.BaseUrl + BaseApiUtil.initialAddress
        post(path, body, callback)
    }

    fun getIPInfo(callback: Callback) {
        val query: HashMap<String, String> = HashMap()
        val body = BaseApiUtil.shared.initPostBody(
            "GET",
            BaseApiUtil.getIPInfoUrl,
            query
        )
        val path = BaseApiUtil.BaseUrl+ BaseApiUtil.initialAddress
        post(path, body, callback)
    }

    fun post(path: String, postBody: String, callback: Callback) {
        val requestBody = postBody.toRequestBody(mediaType)
        val request: Request = Request.Builder()
            .url(path)
            .post(requestBody)
            .build()
        doAsync(request, callback)
    }

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