package com.twm.tools.local

import com.google.gson.Gson
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.math.BigInteger
import java.security.MessageDigest

object BaiduTranslateService: TranslateApi {
    private const val TRANSLATE_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate"
    private const val BAIDU_APPID = "20230809001774667"
    private const val BAIDU_SECRET = ""
    private val client = OkHttpClient.Builder().build()

    override fun translate(source: String, lang: String): String? {
        val salt = System.nanoTime().toString()
        val sign = (BAIDU_APPID + source + salt + BAIDU_SECRET).getMd5()
        val body = FormBody.Builder()
            .add("q", source)
            .add("from", "auto")
            .add("to", lang)
            .add("appid", BAIDU_APPID)
            .add("salt", salt)
            .add("sign", sign)
            .build()
        val request = Request.Builder()
            .post(body)
            .url(TRANSLATE_URL)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .build()
        val response = runCatching {
            client.newCall(request).execute()
        }
        if (response.isFailure) {
            return null
        }
        val result = response.getOrThrow().body?.string() ?: return null
        val translate = Gson().fromJson(
            result, BaiduTranslateResponse::class.java
        )
        return translate.trans_result?.firstOrNull()?.dst
    }

    private fun String.getMd5(): String {
        val md = MessageDigest.getInstance("MD5")
        return BigInteger(1, md.digest(this.toByteArray())).toString(16).padStart(32, '0')
    }
}