package com.kaixed.kchat.network

import androidx.lifecycle.MutableLiveData
import kotlinx.serialization.KSerializer
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import okio.IOException

/**
 * @Author: kaixed
 * @Date: 2024/11/6 22:54
 */
object NetworkHelper {
    fun <T> makeRequest(
        url: String,
        requestBody: Any? = null,
        method: String = "POST",
        serializer: KSerializer<T>
    ): MutableLiveData<NetResult<T>> {
        val netResultLiveData = MutableLiveData<NetResult<T>>()

        netResultLiveData.postValue(NetResult.Loading())

        val callback = object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                netResultLiveData.postValue(NetResult.Error(e))
            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.string()?.let { responseBody ->
                    try {
                        val responseData = Json.decodeFromString(serializer, responseBody)
                        netResultLiveData.postValue(NetResult.Success(responseData))
                    } catch (e: Exception) {
                        netResultLiveData.postValue(NetResult.Error(e))
                    }
                }
            }
        }

        when (method) {
            "POST" -> {
                val json = Json.encodeToString(requestBody)
                NetworkRequest().postAsync(url, json, callback)
            }

            "GET" -> {
                NetworkRequest().getAsync(url, callback)
            }

            else -> {
                netResultLiveData.postValue(NetResult.Error(IllegalArgumentException("不支持的请求方法")))
            }
        }
        return netResultLiveData
    }
}