package com.gh.common.util

import android.net.Uri
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.EnvHelper
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.core.GHThreadFactory
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * 活动相关数据统计辅助类
 */
object ActivityCountHelper {

    private val ACTIVITY_URL_COMMON_PREF =
        if (EnvHelper.isDevEnv) Constants.ACTIVITY_DETAIL_ADDRESS_DEV else Constants.ACTIVITY_DETAIL_ADDRESS
    private var mStayTimeCount = 0
    private var mIsStayTimeCountEnabled = false
    private var mStayTimeArray = arrayOf(5, 10, 20, 40, 80, 160)
    private const val MAX_STAY_TIME = 320
    private val mThreadService: ExecutorService by lazy {
        Executors.newSingleThreadExecutor(GHThreadFactory("STAY_TIME_THREAD"))
    }

    @JvmStatic
    fun postActivityPageEnter(url: String?, entrance: String) {
        if (url?.contains(ACTIVITY_URL_COMMON_PREF) == true) {
            val uri = Uri.parse(url)
            val activityId = uri.getQueryParameter("id") ?: return
            NewFlatLogUtils.logActivityPageEnter(transformEntrance(entrance), activityId)
        }
    }

    private fun transformEntrance(originalEntrance: String): String {
        return when {
            originalEntrance.contains("(启动广告)") -> "开屏页"
            originalEntrance.contains(EntranceConsts.ENTRANCE_WELCOME) -> "首页弹窗"
            originalEntrance.contains("首页tab") -> "首页二级导航"
            originalEntrance.contains("论坛-活动") -> "活动tab"
            originalEntrance.contains("新首页-轮播图") -> "首页banner"
            originalEntrance.contains("资讯") -> "资讯广场"
            else -> originalEntrance
        }
    }

    fun startCountStayTime(url: String) {
        if (url.contains(ACTIVITY_URL_COMMON_PREF)) {
            val uri = Uri.parse(url)
            val activityId = uri.getQueryParameter("id") ?: return
            mIsStayTimeCountEnabled = true
            mThreadService.execute {
                while (mIsStayTimeCountEnabled) {
                    tryWithDefaultCatch {
                        mStayTimeCount++
                        when {
                            mStayTimeCount % MAX_STAY_TIME == 0 -> NewFlatLogUtils.logActivityPageView(
                                MAX_STAY_TIME,
                                activityId
                            )
                            mStayTimeArray.contains(mStayTimeCount) -> NewFlatLogUtils.logActivityPageView(
                                mStayTimeCount,
                                activityId
                            )
                        }
                    }
                    Thread.sleep(1000)
                }
            }
        }
    }

    fun endCountStayTime() {
        mIsStayTimeCountEnabled = false
        mStayTimeCount = 0
    }
}