package com.gh.gamecenter.dsp

import com.gh.gamecenter.common.utils.FixedSizeLinkedHashSet
import com.gh.gamecenter.core.AppExecutor
import com.lightgame.utils.Utils
import okhttp3.OkHttpClient
import okhttp3.Request

object DspReportHelper {

    private const val TAG = "DspReportHelper"
    private val reportCache by lazy { FixedSizeLinkedHashSet<String>(100) }

    fun report(url: String?) {
        url ?: return

        AppExecutor.logExecutor.execute {
            if (reportCache.contains(url)) {
                Utils.log(TAG, "遇到重复上报，自动过滤 （$url）")
                return@execute
            }

            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url(url)
                    .build()

                Utils.log(TAG, "Report is executing: $url")

                val response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    // Add the URL to the cache to prevent duplicate reports
                    reportCache.add(url)

                    Utils.log(TAG, "Report successful: ${response.body?.string()}")
                } else {
                    Utils.log(TAG, "Request failed with code: ${response.code}")
                }
            } catch (e: Exception) {
                Utils.log(TAG, "Request failed: ${e.message}")
            }
        }
    }

}