package com.gh.gamecenter.provider

import android.app.Activity
import android.app.Application
import android.os.Environment
import android.text.TextUtils
import com.gh.gamecenter.BuildConfig
import com.bytedance.hume.readapk.HumeSDK
import com.gh.gamecenter.TeaHelper
import com.gh.gamecenter.core.provider.IFlavorProvider
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import java.io.File

class FlavorProviderImp : IFlavorProvider {

    private var mIsLuckyEnoughToUseTea = true

    override fun init(application: Application, activity: Activity, activateRatio: Int) {

        mIsLuckyEnoughToUseTea = amILucky(activateRatio)

        if (mIsLuckyEnoughToUseTea) {
            TeaHelper.init(application, activity, getChannelStr(application))

            if (HaloApp.getInstance().isBrandNewInstall) {
                SPUtils.setLong(KEY_TIME_OF_BRAND_NEW_INSTALL, System.currentTimeMillis() / 1000)
            } else {
                val shouldSendRetentionLogEvent =
                    SPUtils.getBoolean(KEY_SHOULD_SEND_RETENTION_EVENT, true)
                val installTimeNotToday =
                    !TimeUtils.isToday(SPUtils.getLong(KEY_TIME_OF_BRAND_NEW_INSTALL, System.currentTimeMillis() / 1000))
                if (shouldSendRetentionLogEvent && installTimeNotToday) {
                    logEvent(RETENTION_2D)
                    SPUtils.setBoolean(KEY_SHOULD_SEND_RETENTION_EVENT, false)
                }
            }
        } else {
            SPUtils.setBoolean(KEY_UNLUCKY, true)
        }
    }

    override fun getChannelStr(application: Application): String {
        var channel = HumeSDK.getChannel(application)
        if (channel == null || TextUtils.isEmpty(channel.trim())) {
            channel = "GH_733"
        }
        return channel
    }

    override fun logEvent(content: String) {
        if (mIsLuckyEnoughToUseTea) {
            TeaHelper.onEvent(content)
        }
    }

    private fun amILucky(percentage: Int = 100): Boolean {
        // 若上一次已经标记不幸运了，那就不再进行是否足够幸运的判断
        if (SPUtils.getBoolean(KEY_UNLUCKY)) return false

        val randomNumber = (0..100).random()
        return randomNumber <= percentage
    }

    companion object {
        const val RETENTION_2D = "retention_2d"

        const val KEY_UNLUCKY = "UNLUCKY"
        const val KEY_TIME_OF_BRAND_NEW_INSTALL = "TIME_OF_BRAND_NEW_INSTALL"
        const val KEY_SHOULD_SEND_RETENTION_EVENT = "SHOULD_SEND_RETENTION_EVENT"
    }

}