package com.gh.common.util

import android.content.Context
import android.text.TextUtils
import androidx.annotation.WorkerThread
import com.gh.common.constant.Config
import com.gh.common.simulator.SimulatorGameManager.findDownloadEntityByUrl
import com.gh.common.simulator.SimulatorGameManager.isNewSimulatorInstalled
import com.gh.common.simulator.SimulatorGameManager.isSimulatorGame
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.utils.isLocalDownloadInDualDownloadMode
import com.gh.gamecenter.common.utils.isVGameDownloadInDualDownloadMode
import com.gh.gamecenter.core.AppExecutor.lightWeightIoExecutor
import com.gh.gamecenter.core.AppExecutor.uiExecutor
import com.gh.gamecenter.entity.GameUpdateEntity
import com.gh.gamecenter.feature.entity.*
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.manager.PackagesManager
import com.gh.gamecenter.manager.PackagesManager.isCanUpdate
import com.gh.vspace.VHelper
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus

object GameUtils {
    /**
     * 去除与重复sourceList相同的数据
     */
    fun removeDuplicateData(
        sourceList: MutableList<GameEntity>?,
        rawList: MutableList<GameEntity>?
    ): MutableList<GameEntity>? {
        if (sourceList.isNullOrEmpty() || rawList.isNullOrEmpty()) {
            return rawList
        }
        var id: String
        var i = 0
        while (i < rawList.size) {
            id = rawList[i].id
            for (gameEntity in sourceList) {
                if (id == gameEntity.id) {
                    rawList.removeAt(i)
                    i--
                    break
                }
            }
            i++
        }
        return rawList
    }

    /**
     * 设置下载按钮状态
     */
    fun setDownloadBtnStatus(
        context: Context,
        gameEntity: GameEntity,
        downloadBtn: DownloadButton,
        pluginLocation: PluginLocation?,
        listener: DownloadButton.OnUpdateListener? = null
    ) {
        // getDownloadBtnText 里包括查询数据库、根据包名读取包体 meta 信息等
        lightWeightIoExecutor.execute {
            val status = getDownloadBtnText(
                context = context,
                gameEntity = gameEntity,
                isFromList = true,
                fixedAsVGame = false,
                pluginLocation = pluginLocation
            )
            uiExecutor.execute {
                downloadBtn.text = status
                if (context.getString(com.gh.gamecenter.feature.R.string.pluggable) == status) {
                    downloadBtn.buttonStyle = DownloadButton.ButtonStyle.PLUGIN
                    var pluginDesc = gameEntity.pluginDesc
                    if (pluginDesc.length > 3) pluginDesc = pluginDesc.substring(0, 3)
                    downloadBtn.text = pluginDesc + "化"
                } else {
                    downloadBtn.buttonStyle = DownloadButton.ButtonStyle.NORMAL
                }
                listener?.completion(downloadBtn.text)
            }
        }
    }

    /**
     * 获取下载按钮文案 (相对耗时，请优先在子线程调用)
     *
     * @param isFromList 调用方是否来源自普通列表 （普通列表根据优先级确定是显示成畅玩状态还是普通下载状态）
     * @param fixedAsVGame 固定以畅玩游戏的类型来获取状态
     */
    @WorkerThread
    @JvmStatic
    fun getDownloadBtnText(
        context: Context,
        gameEntity: GameEntity,
        isFromList: Boolean,
        fixedAsVGame: Boolean,
        pluginLocation: PluginLocation?
    ): String {
        if (gameEntity.getApk().size > 1) {
            return ""
        }
        var doneCount = 0 // 下载完成数量
        var pluginCount = 0 // 可插件化数量
        var updateCount = 0 // 可更新数量
        var installCount = 0 // 已安装数量
        var isRelatedEmulatorInstalled = false // 若该游戏是模拟器游戏时其对应的模拟器是否已经安装
        var isInstalledNewSimulator = false // 是否安装新模拟器
        var downloadEntity: DownloadEntity? = null
        var performAsVGame = false // 是否使用了畅玩作为 downloadEntity
        var gh_id: Any?
        apkFor@ for (apkEntity in gameEntity.getApk()) {

            val isInstalledLocally =
                if (gameEntity.isDspGame) {
                    PackageHelper.validLocalPackageNameSet.contains(apkEntity.packageName)
                } else {
                    PackagesManager.isInstalled(apkEntity.packageName)
                }

            // filter by packageName
            val settings = Config.getSettings()
            if (settings != null && gameEntity.getApk().size > 1) {
                for (pkgName in settings.gameDownloadBlackList) {
                    if (pkgName == apkEntity.packageName) {
                        continue@apkFor
                    }
                }
            }

            downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshot(gameEntity)

            // 已安装的畅玩游戏实体
            val vGameDownloadEntity = VHelper.getVDownloadEntitySnapshot(gameEntity.id, apkEntity.packageName)
            performAsVGame = if (fixedAsVGame) {
                true
            } else if (isFromList) {
                if (vGameDownloadEntity == null && isInstalledLocally) {
                    false
                } else {
                    gameEntity.isVGamePreferred()
                }
            } else {
                false
            }

            // 畅玩状态优先，且畅玩实体不为空时将 downloadEntity 置为畅玩实体
            if (performAsVGame && vGameDownloadEntity != null) {
                downloadEntity = vGameDownloadEntity
            } else if (!isFromList) {
                if (!performAsVGame
                    && gameEntity.isDualBtnModeEnabled()
                    && downloadEntity?.isVGameDownloadInDualDownloadMode() == true
                ) {
                    // 下载的任务是由畅玩触发的，并且双下载按钮启用，游戏详情页不需判定为需要安装
                    downloadEntity = null
                } else if (performAsVGame && downloadEntity?.isLocalDownloadInDualDownloadMode() == true) {
                    // 下载的任务是由下载安装触发的，游戏详情页不需判定为需要安装
                    downloadEntity = null
                }
            }

            if (downloadEntity != null) {
                if (downloadEntity.status == DownloadStatus.done) {
                    doneCount++
                } else if (downloadEntity.isPluggable) {
                    pluginCount++
                } else if (downloadEntity.isUpdate) {
                    updateCount++
                }
            }

            if (isCanUpdate(gameEntity.id, apkEntity.packageName, performAsVGame)) {
                updateCount++
            }

            if (isInstalledLocally) {
                gh_id = PackageUtils.getMetaData(context, apkEntity.packageName, "gh_id")
                if (!TextUtils.isEmpty(apkEntity.ghVersion)
                    && !PackageUtils.isSignedByGh(context, apkEntity.packageName)
                    && apkEntity.isShowPlugin(pluginLocation!!)
                ) {
                    pluginCount++
                } else if (gh_id == null || gh_id == gameEntity.id || gameEntity.shouldUseMirrorInfo()) {
                    installCount++
                }
            }

            if (isSimulatorGame(gameEntity)) {
                isInstalledNewSimulator = isNewSimulatorInstalled(context)
                val simulatorDownloadEntity = findDownloadEntityByUrl(apkEntity.url)
                if (simulatorDownloadEntity != null && gameEntity.simulator != null) {
                    val isInstalled =
                        PackageUtils.isInstalledFromAllPackage(context, gameEntity.simulator!!.apk!!.packageName)
                    if (isInstalled) {
                        installCount++
                        isRelatedEmulatorInstalled = true
                    } else {
                        doneCount++
                    }
                }
            }
        }

        if ((isRelatedEmulatorInstalled || isInstalledNewSimulator) && doneCount != 0) {
            return context.getString(com.gh.gamecenter.feature.R.string.launch)
        }

        if (performAsVGame) {
            // 如果 doneCount 为 0 或者数据库为空
            // 表明本地并没有此游戏的数据库数据，需要重新下载
            if (doneCount == 0 || downloadEntity == null || !VHelper.isInstalled(downloadEntity.packageName)) {
                installCount = 0
            } else {
                doneCount = 0
                installCount = 1
            }
        } else {
            if (gameEntity.isDualBtnModeEnabled()) {
                // 双下载按钮模式下，若非更新，排除已安装的情况来影响按钮状态
                if (installCount != 0 && doneCount != 0 && downloadEntity?.isUpdate == false) {
                    doneCount = 0
                }
            }
        }

        return if (doneCount != 0) {
            context.getString(com.gh.gamecenter.feature.R.string.install)
        } else if (pluginCount != 0 && !isSimulatorGame(gameEntity)) {
            context.getString(com.gh.gamecenter.feature.R.string.pluggable)
        } else if (updateCount != 0 && !isSimulatorGame(gameEntity)) {
            context.getString(com.gh.gamecenter.feature.R.string.update)
        } else if (installCount != 0) {
            context.getString(com.gh.gamecenter.feature.R.string.launch)
        } else if ("demo" == gameEntity.downloadStatus) {
            context.getString(com.gh.gamecenter.feature.R.string.attempt)
        } else {
            if (performAsVGame) {
                context.getString(com.gh.gamecenter.feature.R.string.smooth)
            } else {
//                if (Constants.V_GAME == gameEntity.downloadStatus || Constants.V_GAME_32 == gameEntity.downloadStatus) {
//                    val gameCategory = gameEntity.getGameCategory()
//                    if (gameCategory == GameEntity.GameCategory.ONLINE_GAME
//                        || gameCategory == GameEntity.GameCategory.INTERNATIONAL_ONLINE_GAME) {
//                        context.getString(R.string.download)
//                    } else {
//                        context.getString(R.string.attempt)
//                    }
//                } else {
                context.getString(com.gh.gamecenter.feature.R.string.download)
//                }
            }
        }
    }

    /**
     * 获取GameUpdateEntity(插件化)
     */
    fun getGameUpdateEntity(gameEntity: GameEntity, apkEntity: ApkEntity): GameUpdateEntity {
        val gameUpdateEntity = GameUpdateEntity()
        gameUpdateEntity.id = gameEntity.id
        gameUpdateEntity.icon = gameEntity.icon
        gameUpdateEntity.rawIcon = gameEntity.rawIcon
        gameUpdateEntity.iconSubscript = gameEntity.iconSubscript
        gameUpdateEntity.iconFloat = gameEntity.iconFloat
        gameUpdateEntity.name = gameEntity.name
        gameUpdateEntity.packageName = apkEntity.packageName
        gameUpdateEntity.size = apkEntity.size
        gameUpdateEntity.version = apkEntity.version
        gameUpdateEntity.ghVersion = apkEntity.ghVersion
        gameUpdateEntity.url = apkEntity.url
        gameUpdateEntity.platform = apkEntity.getPlatform()
        gameUpdateEntity.etag = apkEntity.etag
        gameUpdateEntity.isPluggable = true
        gameUpdateEntity.tagStyle = gameEntity.tagStyle
        gameUpdateEntity.brief = gameEntity.brief
        gameUpdateEntity.plugin = apkEntity.plugin
        gameUpdateEntity.download = gameEntity.download
        gameUpdateEntity.indexPlugin = gameEntity.indexPlugin
        gameUpdateEntity.pluginDesc = gameEntity.pluginDesc
        gameUpdateEntity.format = apkEntity.format
        gameUpdateEntity.currentVersion = PackageUtils.getVersionNameByPackageName(apkEntity.packageName)
        gameUpdateEntity.category = gameEntity.category
        val pluggableCollection = getPluggableCollectionFromGameEntity(gameEntity, apkEntity.packageName)
        if (pluggableCollection != null) {
            gameUpdateEntity.pluggableCollection = pluggableCollection
        }
        return gameUpdateEntity
    }

    @JvmStatic
    fun getPluggableCollectionFromGameEntity(gameEntity: GameEntity, targetPkg: String?): GameCollectionEntity? {
        // 添加插件化包所在的合集
        for (collectionEntity in gameEntity.collection) {
            if (collectionEntity.packages.contains(targetPkg)) {
                val saveApkEntity = ArrayList<ApkEntity>()
                for (pkg in collectionEntity.packages) {
                    for (apk in gameEntity.getApk()) {
                        if (pkg == apk.packageName) {
                            saveApkEntity.add(apk)
                            break
                        }
                    }
                }
                val apkLinks = gameEntity.apkLink
                if (apkLinks != null) {
                    for (apkLink in apkLinks) {
                        if (apkLink.collection == collectionEntity.id) {
                            val element = ApkEntity()
                            element.apkLink = apkLink
                            if (saveApkEntity.size > apkLink.sort) {
                                saveApkEntity.add(apkLink.sort, element)
                            } else {
                                saveApkEntity.add(element)
                            }
                        }
                    }
                }
                collectionEntity.saveApkEntity = saveApkEntity
                return collectionEntity
            }
        }
        return null
    }

    /**
     * 是否默认以畅玩游戏的形式来处理
     */
    @JvmStatic
    fun shouldPerformAsVGame(gameEntity: GameEntity): Boolean {
        var performActionAsVGame = false

        if (gameEntity.getApk().size != 1) {
            performActionAsVGame = false
        } else {
            when (gameEntity.getGameDownloadButtonMode()) {
                GameEntity.GAME_DOWNLOAD_BUTTON_MODE_VGAME -> performActionAsVGame = true
                GameEntity.GAME_DOWNLOAD_BUTTON_MODE_DOWNLOAD -> performActionAsVGame = false
                GameEntity.GAME_DOWNLOAD_BUTTON_MODE_DUAL -> {
                    val packageName = gameEntity.getApk().first().packageName
                    val isInstalledAtDevice = PackagesManager.isInstalled(packageName)
                    val isInstalledAtVSpace = VHelper.getVDownloadEntitySnapshot(gameEntity.id, packageName) != null

                    performActionAsVGame = if (isInstalledAtDevice && isInstalledAtVSpace) {
                        gameEntity.isVGamePreferred()
                    } else if (isInstalledAtDevice) {
                        false
                    } else if (isInstalledAtVSpace) {
                        true
                    } else {
                        gameEntity.isVGamePreferred()
                    }
                }
            }
        }

        return performActionAsVGame
    }
}
