package com.gh.gamecenter.common.loghub

import androidx.annotation.Keep
import com.gh.gamecenter.common.entity.ExposureEntity
import com.gh.gamecenter.common.exposure.meta.Meta
import com.gh.gamecenter.core.runOnUiThread
import com.google.gson.annotations.SerializedName
import com.volcengine.model.tls.LogItem
import org.json.JSONObject

object LoghubUtils {

    private const val STORE_SIZE = 100

    private val loghubEventSet by lazy { hashSetOf<LoghubEvent>() }

    @JvmStatic
    @JvmOverloads
    fun log(logJson: JSONObject, logStore: String, forcedUpload: Boolean, isFlat: Boolean = false) {
        runOnUiThread {
            val event = LoghubEvent(
                time = (System.currentTimeMillis() / 1000L).toString(),
                content = logJson.toString(),
                logStore = logStore,
                isFlat = isFlat
            )
            loghubEventSet.add(event)

            if (forcedUpload || loghubEventSet.size >= STORE_SIZE) {
                commitSavedLoghubEvents(forcedUpload)
            }
        }
    }

    @JvmStatic
    @JvmOverloads
    fun log(jsonString: String, logStore: String, forcedUpload: Boolean, isFlat: Boolean = false) {
        runOnUiThread {
            val event = LoghubEvent(
                time = (System.currentTimeMillis() / 1000L).toString(),
                content = jsonString,
                logStore = logStore,
                isFlat = isFlat
            )
            loghubEventSet.add(event)

            if (forcedUpload || loghubEventSet.size >= STORE_SIZE) {
                commitSavedLoghubEvents(forcedUpload)
            }
        }
    }

    fun commitSavedLoghubEvents(forcedUpload: Boolean) {
        if (loghubEventSet.isEmpty()) return

        uploadEvents(loghubEventSet.toList(), forcedUpload)
        loghubEventSet.clear()
    }

    private fun uploadEvents(eventList: List<LoghubEvent>, forcedUpload: Boolean) {
        for (event in eventList) {
            val log = LogItem(System.currentTimeMillis())
            // 特殊处理，以下logStore不需要用content包裹数据
            if (event.logStore == "collection" || event.logStore == "common" || event.logStore == "halo-api-device-installed") {
                val contentJson = JSONObject(event.content)
                for (key in contentJson.keys()) {
                    log.addContent(key, contentJson.get(key).toString())
                }
            } else {
                // isFlat为true代表仍需要平铺数据
                if (event.isFlat) {
                    val contentJson = JSONObject(event.content)
                    for (key in contentJson.keys()) {
                        log.addContent(key, contentJson.get(key).toString())
                    }
                    // 新数据使用timestamp字段记录时间
                    log.addContent("timestamp", event.time)
                } else {
                    log.addContent("current time", event.time)
                    log.addContent("content", event.content)
                }
            }

            TLogHubHelper.sendLog(log, event.logStore)
        }
    }

}

@Keep
class SimpleLogContainerEntity(
    var event: String? = null,
    var action: String? = null,
    var meta: Meta? = null,
    var payload: ExposureEntity? = null,
    @SerializedName("link_type")
    var linkType: String? = null,
    @SerializedName("link_id")
    var linkId: String? = null,
    var timestamp: Long? = 0
)