package com.gh.common.xapk

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.activityresult.ActResultRequest
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.entity.SimpleGameEntity
import com.gh.gamecenter.common.entity.SuggestType
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.common.utils.PermissionHelper
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.help.HelpAndFeedbackBridge
import com.lightgame.download.DownloadEntity
import com.lightgame.utils.Utils

object XapkDialogHelper {

    fun showUnzipFailureDialog(context: Context, downloadEntity: DownloadEntity, isManualAction: Boolean) {
        val trigger = if (isManualAction) "手动触发" else "自动触发"
        NewFlatLogUtils.logXApkUnzipFailedDialogShowed(trigger, downloadEntity.gameId, downloadEntity.name)
        DialogHelper.showGuideDialog(
            context = context,
            title = "",
            content = "未授权允许未知来源安装、数据包格式、设备兼容性…等均可能导致解压失败。\n如果开启权限后仍未能解决，请提交反馈帮助我们改进。",
            confirmText = "开启权限",
            cancelText = "提交反馈",
            confirmClickCallback = {
                if (context is AppCompatActivity) {
                    val intent = PermissionHelper.getToInstallPermissionSettingIntent(context)

                    NewFlatLogUtils.logXApkUnzipFailedDialogClick(
                        "开启权限",
                        false,
                        downloadEntity.gameId,
                        downloadEntity.name
                    )

                    // 记录应用重启前需要重解压的信息
                    SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, context.javaClass.name)
                    SPUtils.setString(Constants.SP_XAPK_URL, downloadEntity.url)

                    ActResultRequest(context).startForResult(intent) { resultCode, _ ->
                        if (resultCode == Activity.RESULT_OK) {
                            NewFlatLogUtils.logXApkUnzipFailedDialogClick(
                                "开启权限",
                                true,
                                downloadEntity.gameId,
                                downloadEntity.name
                            )

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                                val pm = context.packageManager
                                val restartIntent = pm.getLaunchIntentForPackage(context.packageName)
                                val mainIntent = Intent.makeRestartActivityTask(restartIntent!!.component)
                                context.startActivity(mainIntent)
                                Runtime.getRuntime().exit(0)
                            } else {
                                XapkInstaller.install(context, downloadEntity, true)
                            }
                        } else if (resultCode == Activity.RESULT_CANCELED) {
                            Utils.log("授予未知应用安装权限失败")
                        }
                    }
                } else if (context is Activity) {
                    PermissionHelper.toInstallPermissionSetting(context)
                }
            },
            cancelClickCallback = {
                val hint = "《" + downloadEntity.name + "》游戏安装包解压失败，问题反馈："
                HelpAndFeedbackBridge.startSuggestionActivity(
                    context,
                    SuggestType.normal,
                    null,
                    hint,
                    SimpleGameEntity(downloadEntity.gameId, downloadEntity.name, downloadEntity.icon)
                )
                NewFlatLogUtils.logXApkUnzipFailedDialogClick(
                    "提交反馈",
                    false,
                    downloadEntity.gameId,
                    downloadEntity.name
                )
            },
            uiModificationCallback = { binding, dialog ->
                binding.headIv.setBackgroundResource(R.drawable.dialog_unzip_failure_head_background)
                binding.titleTv.visibility = View.GONE
                // VectorDrawable 的动态颜色设置只在支持 Vector 的系统版本上生效，为了能方便复用资源不支持的就用默认颜色，又不是不能用！
                binding.closeIv.setColorFilter(Color.WHITE)
                binding.contentTv.setLineSpacing(5.0F.dip2px().toFloat(), 1.0F)
                binding.closeContainer.setOnClickListener {
                    NewFlatLogUtils.logXApkUnzipFailedDialogClick(
                        "关闭",
                        false,
                        downloadEntity.gameId,
                        downloadEntity.name
                    )
                    dialog.dismiss()
                }
            },
            extraConfig = DialogHelper.Config(showCloseIcon = true)
        )
    }

}