package com.base.scanqrclear.utils

import com.base.scanqrclear.bean.OpenFoodBean
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject


object OpenFoodFactsUtils {


    private val TAG = "OpenFoodFactsUtils"

    //https://world.openfoodfacts.org/api/v3/product/4890008100309.json
    fun getOpenFood(qrCode: String): OpenFoodBean? {

        try {
            val url = "https://world.openfoodfacts.org/api/v3/product/$qrCode.json"
            val client = OkHttpClient()
            val request = Request.Builder()
                .url(url)
                .get()
                .addHeader("User-Agent", "okhttp/4.10.0")
                .addHeader("Accept-Encoding", "gzip")
                .addHeader(
                    "base",
                    "{\"device_id\":\"8e0ca12e-1022-4d88-8b97-dd6aa3e5d4bd\",\"platform\":\"1\",\"device_model\":\"Xiaomi MI 9\",\"app_lang\":\"zh_CN\",\"sys_lang\":\"zh_CN\",\"client_version\":\"1.25.0\",\"inner_version\":10012500,\"sys_version\":\"11\",\"channel\":\"\",\"country\":\"CN\",\"time_zone\":\"GMT-6\",\"package_name\":\"com.healthapplines.scanner.ai\",\"guid\":\"8e0ca12e-1022-4d88-8b97-dd6aa3e5d4bd\",\"network_type\":\"NETWORK_WIFI\"}"
                )
                .addHeader("version", "10001")
                .addHeader("nonce", "ckCkrQ5flf")
                .addHeader("timestamp", "${System.currentTimeMillis()}")
                .addHeader(
                    "token",
                    "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhMWVjZmM1OS02Y2JkLTQwNmEtYjM4Zi01NzU2Y2ExNTY3OGQiLCJpYXQiOjE3MzcwODMzNzksInN1YiI6IjEyNzcwMDkifQ.yTdcAZ5DYC9smu6YhTkL7T2kW0CwGiP1XfX3RJUHmJM"
                )
                .addHeader("sign", "4B8F5E4DB16324FB6CC4A3BA2AD83E15")
                .build()

            val response = client.newCall(request).execute()
            val body = response.body?.string() ?: ""
            LogEx.logDebug(TAG, "body=$body")
            val jsonObject = JSONObject(body)
            val productJson = jsonObject.getJSONObject("product").toString()
            val bean = Gson().fromJson(productJson, OpenFoodBean::class.java)
            bean.qrString = qrCode
            bean.dataSource = url
            return bean
        } catch (e: Exception) {

        }

        return null

    }
}