package com.gh.common.util

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.utils.isVGameDownloadInDualDownloadMode
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.GameInstall
import com.gh.gamecenter.manager.PackagesManager
import com.gh.vspace.VHelper

object PackageLauncher {

    /**
     * 自动选择启动已安装的畅玩或本地已安装的游戏
     * 仅适用于 gameEntity 只有一个 apk 的情况
     */
    @JvmStatic
    fun launch(
        context: Context,
        gameEntity: GameEntity,
        location: String? = null
    ) {
        if (gameEntity.getApk().isEmpty() || gameEntity.getApk().size > 1) {
            return
        }

        val packageName = gameEntity.getApk().first().packageName

        // 根据下载按钮类型进行进行不一样的处理
        when (gameEntity.getGameDownloadButtonMode()) {
            GameEntity.GAME_DOWNLOAD_BUTTON_MODE_DOWNLOAD -> {
                launchApp(context, gameEntity, packageName)
            }

            GameEntity.GAME_DOWNLOAD_BUTTON_MODE_VGAME -> {
                VHelper.installOrLaunch(context as AppCompatActivity, gameEntity, location)
            }

            GameEntity.GAME_DOWNLOAD_BUTTON_MODE_DUAL -> {
                val vGameIsInstalled = VHelper.isInstalled(packageName)
                val localGameIsInstalled = PackageUtils.isInstalled(context, packageName)

                when {
                    vGameIsInstalled && localGameIsInstalled -> {
                        if (gameEntity.isVGamePreferred()) {
                            VHelper.installOrLaunch(context as AppCompatActivity, gameEntity, location)
                        } else {
                            launchApp(context, gameEntity, packageName)
                        }
                    }

                    vGameIsInstalled -> {
                        VHelper.installOrLaunch(context as AppCompatActivity, gameEntity, location)
                    }

                    localGameIsInstalled -> {
                        launchApp(context, gameEntity, packageName)
                    }

                    else -> {
                        val downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshot(gameEntity)
                        if (downloadEntity?.isVGameDownloadInDualDownloadMode() == true) {
                            VHelper.installOrLaunch(context as AppCompatActivity, gameEntity, location)
                        } else {
                            ToastUtils.toast("下载异常，请重新下载")
                        }
                    }
                }
            }
        }
    }

    /*
     * 启动应用
     */
    @JvmStatic
    fun launchApp(
        context: Context,
        gameEntity: GameEntity? = null,
        packageName: String?
    ) {
        if (packageName.isNullOrEmpty()) {
            ToastUtils.toast("启动失败")
            return
        }

        try {
            val intent = context.applicationContext.packageManager.getLaunchIntentForPackage(packageName)
            if (intent != null) {
                context.startActivity(intent)
            } else {
                ToastUtils.toast("启动失败")
            }
        } catch (e: Exception) {
            ToastUtils.toast( "启动失败")
        }

        try {
            // 获取 GameInstall 实体，用于记录启动日志用
            val gameInstall = if (gameEntity != null) {
                GameInstall.transformGameInstall(gameEntity, packageName)
            } else {
                PackagesManager.getInstalledList().find { it.packageName == packageName }
            }

            if (gameInstall != null) {
                NewFlatLogUtils.logGameLaunch(
                    gameId = gameInstall.id ?: "unknown",
                    gameName = gameInstall.name ?: "unknown",
                    gameCategory = gameInstall.category ?: "unknown",
                    downloadStatus = if (gameInstall.downloadStatus == "demo") "试玩" else "下载"
                )
            }
        } catch (e: RuntimeException) {
            // 都 DeadSystemException 了，还想啥日志上报
        }
    }

}