package com.gh.gamecenter.core.utils

import android.text.TextUtils
import com.gh.gamecenter.core.BuildConfig
import com.lightgame.utils.Utils
import io.sentry.Sentry
import io.sentry.SentryEvent
import io.sentry.SentryLevel
import io.sentry.protocol.Message

object SentryHelper {

    /**
     * 注意 tag-key 不支持中文
     */
    fun onEvent(eventId: String, vararg kv: String?) {
        val sentryEvent = SentryEvent()
        val message = Message()
        message.message = eventId
        sentryEvent.message = message
        sentryEvent.level = SentryLevel.INFO

        for (i in kv.indices) {
            if (i % 2 != 0) {
                val key = kv[i - 1]
                val value = kv[i]
                if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
                    sentryEvent.setTag(key!!, value!!)
                    if (BuildConfig.DEBUG && isContainChinese(key)) {
                        throw RuntimeException("tag-key 不支持中文")
                    }
                }
            }
        }

        Utils.log("Sentry", "$eventId + [${kv.joinToString(" , ")}]")
        Sentry.captureEvent(sentryEvent)
    }

    // 判断一个字符串是否含有中文
    private fun isContainChinese(str: String?): Boolean {
        if (str == null) return false
        for (c in str.toCharArray()) {
            if (c.toInt() in 0x4E00..0x9FA5) return true
        }
        return false
    }
}
