package com.gh.gamecenter.provider

import android.app.Activity
import android.app.Application
import android.text.TextUtils
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.SMHelper
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.provider.IFlavorProvider
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.halo.assistant.HaloApp
import com.tencent.vasdolly.helper.ChannelReaderUtil

class FlavorProviderImp : IFlavorProvider {

    private var isInit = false

    private val pendingEvent = arrayListOf<String>()

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

        isInit = true
        if (HaloApp.getInstance().isBrandNewInstall) {
            logEvent("EVENT_ACTIVE")
            SPUtils.setLong("TIME_OF_BRAND_NEW_INSTALL", System.currentTimeMillis() / 1000)
        } else {
            val shouldSendRetentionLogEvent =
                SPUtils.getBoolean("SHOULD_SEND_RETENTION_EVENT", true)
            val installTimeNotToday =
                !TimeUtils.isToday(SPUtils.getLong("TIME_OF_BRAND_NEW_INSTALL", System.currentTimeMillis() / 1000))
            if (shouldSendRetentionLogEvent && installTimeNotToday) {
                logEvent("EVENT_NEXTDAY_STAY")
                SPUtils.setBoolean("SHOULD_SEND_RETENTION_EVENT", false)
            }
        }
        pendingEvent.forEach(SMHelper::onEvent)
        pendingEvent.clear()
    }

    override fun getChannelStr(application: Application): String {
        var channel = ChannelReaderUtil.getChannel(application)

        if (channel == null || TextUtils.isEmpty(channel.trim())) {
            channel = SM_CHANNEL
        }
        return channel
    }

    override fun logEvent(content: String) {
        if (isInit) {
            SMHelper.onEvent(content)
        } else {
            pendingEvent.add(content)
        }
    }

    override fun logCoreEvent() {
        logEvent("EVENT_KEY_PATH_OPTIMIZATION")
        if (BuildConfig.ACTIVATE_REPORTING_RATIO == 1) {
            AppExecutor.uiExecutor.executeWithDelay({
                ToastUtils.toast("关键行为 EVENT_KEY_PATH_OPTIMIZATION")
            }, 500)
        }
    }

    companion object {
        private const val SM_CHANNEL = "SM-GHZS-01"
    }
}