package com.xyzshell.andinfo.utils

import android.util.Base64
import com.google.gson.Gson
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

class WebService {
    private val client = OkHttpClient()
    val gson = Gson()
    // AES 密钥 (必须是 16/24/32 字节)
    private val aesKey = "e67cbcee5e573d1b"

    // AES 加密
    fun encrypt(plainText: String): String {
        return try {
            val secretKey = SecretKeySpec(aesKey.toByteArray(), "AES")
            val cipher = Cipher.getInstance("AES")
            cipher.init(Cipher.ENCRYPT_MODE, secretKey)
            val encryptedBytes = cipher.doFinal(plainText.toByteArray())
            Base64.encodeToString(encryptedBytes, Base64.NO_WRAP)
        } catch (e: Exception) {
            throw Exception("加密失败: ${e.message}")
        }
    }
    fun postData(url: String, jsonData: String, callback: (String?, Exception?) -> Unit) {
        val mediaType = "application/json; charset=utf-8".toMediaType()
        val body = jsonData.toRequestBody(mediaType)

        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback(null, e)
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (it.isSuccessful) {
                        callback(it.body?.string(), null)
                    } else {
                        callback(null, Exception("HTTP ${it.code}"))
                    }
                }
            }
        })
    }

    // 同步版本
    fun postDataSync(url: String, jsonData: String): String? {
        val mediaType = "application/json; charset=utf-8".toMediaType()
        val body = jsonData.toRequestBody(mediaType)

        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

        client.newCall(request).execute().use { response ->
            return if (response.isSuccessful) {
                response.body?.string()
            } else {
                null
            }
        }
    }

    // 序列化对象为 JSON
    fun <T> toJson(obj: T): String {
        return gson.toJson(obj)
    }

    // 反序列化 JSON 为对象
    inline fun <reified T> fromJson(json: String): T? {
        return try {
            gson.fromJson(json, T::class.java)
        } catch (e: Exception) {
            null
        }
    }

    // 带序列化的 POST 请求
    fun <T> postObject(url: String, obj: T, callback: (String?, Exception?) -> Unit) {
        val jsonData = toJson(obj)
        postData(url, jsonData, callback)
    }
    // 带序列化和反序列化的 POST 请求
    inline fun <reified T, reified R> postAndParse(
        url: String,
        obj: T,
        crossinline callback: (R?, Exception?) -> Unit
    ) {
        val jsonData = toJson(obj)
        postData(url, jsonData) { response, error ->
            if (error != null) {
                callback(null, error)
            } else if (response != null) {
                val result = fromJson<R>(response)
                callback(result, null)
            } else {
                callback(null, Exception("Empty response"))
            }
        }
    }
}