package com.gh.common.util

import com.gh.gamecenter.common.constant.Constants
import com.gh.common.dialog.DeviceRemindDialog
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.PluginLocation
import com.google.gson.reflect.TypeToken
import com.halo.assistant.HaloApp

object RecommendPopupHelper {

    fun getRecommendPopup(gameEntity: GameEntity?, popups: ArrayList<RecommendPopupEntity>?): RecommendPopupEntity? {
        if (gameEntity == null || popups.isNullOrEmpty()) return null

        //判断是否触发设备弹窗
        val pair = DeviceRemindDialog.shouldShowDeviceRemindDialog(gameEntity)
        if (pair.first) return null

        //判断是否为多版本游戏
        if (gameEntity.getApk().isEmpty() || gameEntity.getApk().size > 1) return null

        val downloadBtnText = GameUtils.getDownloadBtnText(HaloApp.getInstance(), gameEntity, PluginLocation.only_game)
        val filterEntities = arrayListOf<RecommendPopupEntity>()

        loop@ for (entity in popups) {
            //判断是否符合下载类型
            val downloadType = entity.recommendPackage.getDownloadType()
            if (!downloadType.contains(downloadBtnText)) continue

            //判断是否符合安装包大小限制
            val minSize = entity.recommendPackage.minSize
            val sizeStr = gameEntity.getApk()[0].size ?: continue
            val size = sizeStr.substring(0, sizeStr.length - 2).toFloat()
            if (size < minSize) continue

            //判断是否符合包名限制
            val nameRule = entity.recommendPackage.nameRule
            val packages = entity.recommendPackage.details
            val installedPackages = PackageUtils.getAllPackageNameIncludeGh(HaloApp.getInstance())
            var isMatchSuccess = true
            val checkInstalled: (splitPackages: List<String>) -> Boolean = {
                var isInstalled = false
                it.forEach { packageName ->
                    if (installedPackages.contains(packageName)) {
                        isInstalled = true
                        return@forEach
                    }
                }
                isInstalled
            }
            when (nameRule) {
                "installed" -> {
                    //设备上安装了指定的包名才生效(需全部满足)
                    packages.forEach {
                        val splitPackages = it.split("、")
                        val isInstalled = checkInstalled(splitPackages)
                        if (!isInstalled) {
                            isMatchSuccess = false
                            return@forEach
                        }
                    }
                }
                "uninstalled" -> {
                    //设备上未安装指定的包名才生效(需全部满足)
                    packages.forEach {
                        val splitPackages = it.split("、")
                        val isInstalled = checkInstalled(splitPackages)
                        if (isInstalled) {
                            isMatchSuccess = false
                            return@forEach
                        }
                    }
                }
                else -> {
                    isMatchSuccess = true
                }
            }
            if (!isMatchSuccess) continue

            filterEntities.add(entity)
        }

        return if (filterEntities.isEmpty()) {
            null
        } else {
            val recommendPopupEntity = filterEntities[0]
            if (checkFrequencyIsMatch(recommendPopupEntity)) {
                recommendPopupEntity
            } else {
                null
            }
        }
    }

    fun checkFrequencyIsMatch(entity: RecommendPopupEntity): Boolean {
        //判断是否符合通知频率 一次once, 累计次数count, 每周一次weekly, 每天一次daily, 每次always
        val plan = entity.notice.plan
        val times = entity.notice.times
        //[{"popupId":"6074ff265b58135844aec523","showTime":1618391319457,"count":1}]
        val recordStr = SPUtils.getString(Constants.SP_RECOMMEND_POPUP)
        val type = object : TypeToken<ArrayList<RecommendRecord>>() {}.type
        val records = GsonUtils.gson.fromJson<ArrayList<RecommendRecord>>(recordStr, type)
            ?: arrayListOf()
        val recommendRecord = records.find { it.popupId == entity.id }
        val showTime = recommendRecord?.showTime ?: 0L
        val count = recommendRecord?.count ?: 0
        when (plan) {
            "once" -> {
                if (recommendRecord != null) return false
            }
            "count" -> {
                if (count >= times) return false
            }
            "weekly" -> {
                if (TimeUtils.isThisWeek(showTime)) return false
            }
            "daily" -> {
                if (TimeUtils.isToday(showTime)) return false
            }
            "always" -> {
                //do nothing
            }
        }
        return true
    }

    fun saveRecord(popup: RecommendPopupEntity) {
        val plan = popup.notice.plan
        val recordStr = SPUtils.getString(Constants.SP_RECOMMEND_POPUP)
        val type = object : TypeToken<ArrayList<RecommendRecord>>() {}.type
        val records = GsonUtils.gson.fromJson<ArrayList<RecommendRecord>>(recordStr, type)
            ?: arrayListOf()
        val recommendRecord = records.find { it.popupId == popup.id }
        if (recommendRecord == null) {
            records.add(RecommendRecord(popup.id, System.currentTimeMillis(), 1))
        } else {
            if (plan == "count") {
                recommendRecord.count = recommendRecord.count + 1
            }
            recommendRecord.showTime = System.currentTimeMillis()

        }
        SPUtils.setString(Constants.SP_RECOMMEND_POPUP, GsonUtils.toJson(records))
    }
}