package com.gh.common.simulator

import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.view.Gravity
import androidx.core.content.FileProvider
import com.gh.common.constant.Config
import com.gh.common.util.LogUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.EmptyCallback
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.feature.entity.GameEntity
import com.halo.assistant.HaloApp
import com.lightgame.download.DownloadEntity
import com.lightgame.utils.AppManager
import io.reactivex.Single
import java.io.ByteArrayOutputStream
import java.io.File

object NewSimulatorGameManager {

    private const val KEY_GAME_ICON = "GAME_ICON"
    private const val KEY_GAME_ID = "GAME_ID"
    private const val KEY_GAME_NAME = "GAME_NAME"
    private const val KEY_GAME_PACKAGE_NAME = "GAME_PACKAGE_NAME"
    private const val KEY_GAME_PACKAGE_PATH = "GAME_PACKAGE_PATH"
    private const val KEY_GAME_PACKAGE_LAST_MODIFICATION = "GAME_PACKAGE_LAST_MODIFICATION"
    private const val KEY_GAME_PACKAGE_EXTENSION = "GAME_PACKAGE_EXTENSION"
    private const val KEY_GAME_PACKAGE_SDCARD_PATH = "GAME_PACKAGE_SDCARD_PATH" // boolean 是否sdcard文件路径
    private const val KEY_GAME_EMU_SYSTEM = "GAME_EMU_SYSTEM"
    private const val KEY_EMU_ID = "EMU_ID"
    private const val KEY_EMU_NAME = "EMU_NAME"
    private const val KEY_USE_DEBUG_API = "USE_DEBUG_API"
    private const val KEY_META = "META"

//    private const val GH_RETRO_EMU_APP_PACKAGE_NAME = "com.gh.retroemu"
    private const val GH_RETRO_EMU_APP_LAUNCHER_ACTIVITY_NAME = "com.gh.retroemu.ui.SplashActivity"


    private const val NEW_SIMULATOR_SHOW_ALERT_TAG = "-news-simulator-show-alert"

    /**
     * 后台模拟器管理上传新版本模拟器（显示状态），且检测用户有安装旧版本模拟器  每日弹出一次更新弹框
     */
    @JvmStatic
    fun shouldShowUpdateNewSimulatorAlert(context: Context): Boolean {
        val isUploadNewsSimulator = Config.getNewSimulatorEntitySetting()?.active ?: false
        val isInstallOld = SimulatorGameManager.isOldSimulatorInstalled(context)
        val showAlertTag = SPUtils.getString(NEW_SIMULATOR_SHOW_ALERT_TAG, "")
        val todayIsShow = showAlertTag == TimeUtils.getToday()//当天是否弹出过一次
        val isInstalledNewSimulator = SimulatorGameManager.isNewSimulatorInstalled(context)
        return (isUploadNewsSimulator && !todayIsShow && isInstallOld && !isInstalledNewSimulator)
    }

    /**
    * 弹出更新弹框
    */
    @JvmStatic
    fun showUpdateNewsSimulator(context: Context, callback: EmptyCallback? = null){
        NewFlatLogUtils.logSimulatorUpdateAlertShow()
        DialogHelper.showDialog(
            context,
            "更新提示",
            "光环助手近期对模拟器进行升级，优化游戏体验！\n但更新后可能会导致原先的游戏存档数据无法使用（可在模拟器管理中安装新版本模拟器）",
            "更新",
            "取消",
            confirmClickCallback = {
                NewFlatLogUtils.logSimulatorUpdateAlertClick("更新")
                val simulator = Config.getNewSimulatorEntitySetting()
                if (simulator != null) {
                    SimulatorDownloadManager.getInstance().showDownloadingDialog(context, simulator)
                }
            },
            cancelClickCallback = {
                callback?.onCallback()
                NewFlatLogUtils.logSimulatorUpdateAlertClick("取消")
            },
            uiModificationCallback = { binding ->
                binding.contentTv.gravity = Gravity.START
                binding.contentTv.setTextColor(R.color.text_subtitle.toColor(context))
            },
            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
        SPUtils.setString(NEW_SIMULATOR_SHOW_ALERT_TAG, TimeUtils.getToday())
    }


    /**
     * 通过模拟器启动游戏
     */
    @SuppressLint("CheckResult")
    @JvmStatic
    fun launchGameViaSimulator(downloadEntity: DownloadEntity, gameEntity: GameEntity) {
        val newSimulator = Config.getNewSimulatorEntitySetting() ?: return
        val gameIcon = gameEntity.icon ?: gameEntity.rawIcon ?: ""
        Single.just(ImageUtils.getCachedUrl(gameIcon))
            .flatMap {
                SimulatorGameManager.getBitmapFormCache(it)
            }.map {
                BitmapUtils.compressBitmap(it, 100)
            }.map {
                val baos = ByteArrayOutputStream()
                it.compress(Bitmap.CompressFormat.WEBP, 90, baos)
                baos.toByteArray()
            }
            .compose(singleToMain())
            .subscribe({
                val gamePackageFileUri = FileProvider.getUriForFile(
                    HaloApp.getInstance(),
                    BuildConfig.APPLICATION_ID,
                    File(downloadEntity.path)
                )
                HaloApp.getInstance().grantUriPermission(
                    SimulatorGameManager.NEW_SIMULATOR_PACKAGE_NAME,
                    gamePackageFileUri,
                    Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or
                            Intent.FLAG_GRANT_READ_URI_PERMISSION or
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION // 冗余，以备不时之需
                )

                val intent = Intent()
                intent.setClassName(SimulatorGameManager.NEW_SIMULATOR_PACKAGE_NAME, GH_RETRO_EMU_APP_LAUNCHER_ACTIVITY_NAME)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.data = gamePackageFileUri
                gameEntity.getApk().safelyGetInRelease(0)?.let { apk ->
                    intent.putExtra(KEY_GAME_PACKAGE_NAME, apk.packageName)
                    intent.putExtra(KEY_GAME_PACKAGE_EXTENSION, apk.format)
                }
                intent.putExtra(KEY_GAME_NAME, downloadEntity.name)
                intent.putExtra(KEY_GAME_ICON, it)
                intent.putExtra(KEY_GAME_PACKAGE_PATH, downloadEntity.path) // 游戏包文件路径，冗余参数)
                intent.putExtra(KEY_GAME_PACKAGE_SDCARD_PATH, true)
                intent.putExtra(KEY_GAME_PACKAGE_LAST_MODIFICATION, File(downloadEntity.path).lastModified()) // 游戏包文件修改时间
                intent.putExtra(KEY_GAME_EMU_SYSTEM, gameEntity.simulatorType) // 模拟器类型
                intent.putExtra(KEY_GAME_ID, gameEntity.id)
                // TODO 补充光环模拟器的游戏 id
                intent.putExtra(KEY_EMU_ID, newSimulator.apk?.id) // 光环模拟器.apk gameId
                intent.putExtra(KEY_EMU_NAME, "光环模拟器") // 光环模拟器.apk name
                intent.putExtra(KEY_USE_DEBUG_API, EnvHelper.isDevEnv) // // 游戏来源是否为dev后台 (是否来源于测试环境)
                intent.putExtra(KEY_META, LogUtils.getMetaObject().toString())

                try {
                    AppManager.getInstance().recentActiveActivity?.startActivity(intent)
                } catch (e: ActivityNotFoundException) {
                    ToastUtils.showToast("模拟器安装错误")
                }

                SimulatorGameManager.recordPlaySimulatorGames(gameEntity.id)
            }, {
                ToastUtils.showToast("跳转失败")
            })
    }

}