package com.gh.vspace.shortcut

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Matrix
import android.view.WindowManager
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.fragment.app.FragmentActivity
import com.gh.gamecenter.MainActivity
import com.gh.gamecenter.common.callback.BiCallback
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.PermissionHelper
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.vspace.VHelper
import com.lg.vspace.VirtualAppManager
import com.muugi.shortcut.core.Executor
import com.muugi.shortcut.core.Shortcut
import com.muugi.shortcut.core.ShortcutAction

/**
 * @author : liujiarui
 * date : 2023/3/20
 * description : 动态创建快捷方式管理类
 */
class ShortcutManager private constructor() {

    private var mResult: OnCreateShortcutResult? = null

    private val mDelegateManager by lazy { VirtualAppManager.get() }

    private val mShortcutAction: ShortcutAction by lazy {
        object : ShortcutAction() {
            override fun showPermissionDialog(context: Context, check: Int, executor: Executor) {
                runOnUiThread {
                    try {
                        mResult?.showPermissionDialog(executor)
                    } catch (e: WindowManager.BadTokenException) {
                        ToastUtils.toast("创建快捷方式失败，请稍后再试")
                    }
                }
            }

            override fun onCreateAction(
                requestPinShortcut: Boolean,
                check: Int,
                executor: Executor
            ) {
                if (requestPinShortcut) {
                    mResult?.success()
                } else {
                    //创建失败估计还是权限问题，直接弹出跳转权限设置
                    runOnUiThread {
                        try {
                            mResult?.showPermissionDialog(executor)
                        } catch (e: WindowManager.BadTokenException) {
                            ToastUtils.toast("创建快捷方式失败，请稍后再试")
                        }
                    }
                }
            }

            override fun onUpdateAction(updatePinShortcut: Boolean) {
                if (updatePinShortcut) {
                    mResult?.success()
                } else {
                    mResult?.failed()
                }
            }
        }
    }

    private val mCallback: Shortcut.Callback by lazy {
        object : Shortcut.Callback {
            override fun onAsyncCreate(id: String, label: String) {
                //ToastUtils.showToast("桌面图标创建成功~")
            }
        }
    }

    /**
     * 知道游戏id和包名，创建桌面图标
     */
    fun tryCreateShortCut(context: Context, gameId: String, gamePkg: String, result: OnCreateShortcutResult) {
        val downloadEntity = VHelper.getVDownloadEntitySnapshot(gameId, gamePkg)
        val createShortcutLambda = {
            runOnUiThread {
                if (downloadEntity == null) {
                    result.failed()
                } else {
                    val gameEntity = VHelper.toGameEntity(downloadEntity)
                    tryCreateShortCut(context, gameEntity, result)
                }
            }
        }
        if (VHelper.isInnerInstalled(gamePkg)) {
            createShortcutLambda.invoke()
        } else {
            VHelper.postOnInitialized(createShortcutLambda)
        }
    }


    /**
     * 创建快捷方式
     */
    fun tryCreateShortCut(context: Context, gameEntity: GameEntity, result: OnCreateShortcutResult) {
        mResult = result
        val activity = context as? FragmentActivity ?: return
        if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
            PermissionHelper.checkShortcutPermission(activity,
                onGrantedCallback = {
                    createShortcut(context, gameEntity)
                },
                onDeniedCallback = {
                    mResult?.showPermissionDialog(null)
                })
        } else {
            mResult?.showPermissionDialog(null)
        }
    }

    /**
     * 创建快捷方式
     */
    private fun createShortcut(context: Context, gameEntity: GameEntity) {
        val gameId = gameEntity.id
        val gameName = gameEntity.name ?: ""
        val gameIcon = gameEntity.icon ?: ""
        val dynamicShortcuts = ShortcutManagerCompat.getShortcuts(context, ShortcutManagerCompat.FLAG_MATCH_PINNED)
        val shortcutExists = dynamicShortcuts.find { it.id == gameId }
        if (shortcutExists != null) {
            ShortcutManagerCompat.enableShortcuts(
                context, listOf(shortcutExists)
            )
            mResult?.exist()
            return
        }
        ImageUtils.getBitmap(gameIcon, object : BiCallback<Bitmap, Boolean> {
            override fun onFirst(first: Bitmap) {
                // 压缩图片
                val bitmap = compressImage(first)
                val shortcutInfoIntent = getGameIntent(context, gameEntity)
                shortcutInfoIntent.run {
                    val info = ShortcutInfoCompat.Builder(context, gameId)
                        .setIcon(IconCompat.createWithBitmap(bitmap))
                        .setShortLabel(gameName)
                        //.setAlwaysBadged() // 设置图标角标为应用角标
                        .setIntent(this)
                        .build()
                    // 创建快捷方式
                    Shortcut.singleInstance.requestPinShortcut(
                        context = context,
                        shortcutInfoCompat = info,
                        updateIfExit = false,
                        fixHwOreo = true,
                        shortcutAction = mShortcutAction
                    )
                }
            }

            override fun onSecond(second: Boolean) {
                mResult?.failed()
            }
        })
    }

    /**
     * 动态删除快捷方式
     * 暂时只能在原生系统禁用快捷方式
     */
    fun removeShortcut(context: Context, gameEntity: GameEntity) {
        val gameId = gameEntity.id
        val gameName = gameEntity.name ?: ""
        val dynamicShortcuts = ShortcutManagerCompat.getShortcuts(context, ShortcutManagerCompat.FLAG_MATCH_PINNED)
        val shortcutExists = dynamicShortcuts.find { it.id == gameId }
        if (shortcutExists != null) {
            /*ShortcutManagerCompat.disableShortcuts(
                context, listOf(gameId), "$gameName 已经卸载"
            )*/
            //暂时不禁用图标，让跳转到光环助手再提示游戏已经卸载。但是尝试移除图标
            ShortcutManagerCompat.removeLongLivedShortcuts(context, listOf(gameId))
        }
    }



    /**
     * 获取游戏快捷方式跳转Intent
     * 先启动光环助手，然后跳转游戏
     */
    private fun getGameIntent(context: Context, gameEntity: GameEntity): Intent {
        val intent = Intent(context, MainActivity::class.java)
        intent.action = Intent.ACTION_VIEW
        intent.putExtra(EntranceConsts.KEY_REQUIRE_REDIRECT, true)
        intent.putExtra(EntranceConsts.KEY_TO, EntranceConsts.HOST_LAUNCH_VM_GAME)
        intent.putExtra(EntranceConsts.KEY_GAME_PKG, gameEntity.getUniquePackageName())
        return intent
    }

    // Bitmap尺寸超过300*300就压缩
    private fun compressImage(bitmap: Bitmap): Bitmap {
        return if (bitmap.byteCount > 300 * 300 * 4) {
            val width = bitmap.width.toFloat()
            val height = bitmap.height.toFloat()
            val matrix = Matrix()
            val scaleWidth = 300 / width
            val scaleHeight = 300 / height
            matrix.postScale(scaleWidth, scaleHeight)
            Bitmap.createBitmap(bitmap, 0, 0, width.toInt(), height.toInt(), matrix, true)
        } else bitmap
    }

    companion object {
        private val mShortcutManager = ShortcutManager()
        fun getInstance(): ShortcutManager {
            Shortcut.singleInstance.addShortcutCallback(mShortcutManager.mCallback)
            return mShortcutManager
        }
    }
}