package com.gh.common.util

import com.gh.gamecenter.common.utils.toastInInternalRelease
import com.gh.gamecenter.common.utils.tryCatchInRelease
import com.gh.gamecenter.entity.HomePluggableFilterEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.room.AppDatabase

/**
 * 首页插件化区域辅助类
 */
object HomePluggableHelper {

    private val mHomePluggableFilterDao by lazy { AppDatabase.getInstance().homePluggableFilterDao() }

    @JvmStatic
    fun setHomePluggableFilterData(gameEntity: GameEntity, isNever: Boolean) {
        val apkList = gameEntity.getApk()
        if (apkList.isNotEmpty()) {
            val apk = apkList.first()
            val tag = if (isNever) "never" else apk.version ?: ""
            tryCatchInRelease {
                mHomePluggableFilterDao.addData(
                    HomePluggableFilterEntity(
                        pkgName = apk.packageName,
                        tag = tag,
                        active = isNever
                    )
                )
            }
        }
    }

    @JvmStatic
    fun showHomePluggable(gameEntity: GameEntity): Boolean {
        val apkList = gameEntity.getApk()
        if (apkList.isNotEmpty()) {
            val apk = apkList.first()
            tryCatchInRelease {
                val filterData = mHomePluggableFilterDao.getDataByPkgName(apk.packageName)
                if (filterData?.active == true) {
                    val filterTag = filterData.tag
                    return filterTag != "never" && apk.version != filterTag
                }
            }
        }
        return true
    }

    @JvmStatic
    fun getPermanentInactivePluggablePackage(): List<HomePluggableFilterEntity>? {
        tryCatchInRelease {
            return mHomePluggableFilterDao.getDataByTag("never")
        }
        return emptyList()
    }

    @JvmStatic
    fun activationFilterData() {
        try {
            val filterList = mHomePluggableFilterDao.getDataByActive(false)

            if (filterList != null) {
                for (entity in filterList) {
                    entity.active = true
                }
                mHomePluggableFilterDao.addData(filterList)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            toastInInternalRelease("插件化筛选出现异常")
        }
    }
}