package com.gh.common.util

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.gh.common.constant.Config
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.entity.NewApiSettingsEntity
import com.lightgame.utils.Utils

import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.enlargeTouchArea
import com.gh.gamecenter.common.utils.setDrawableEnd
import com.gh.gamecenter.core.utils.SPUtils

/**
 * 处理厂商纯净/安全模式的辅助类
 */
object PureModeHelper {

    private const val TAG = "PureModeHelper"

    private const val HW = "HUAWEI"

    private const val HW_PURE_MODE_STATE = "pure_mode_state"
    private const val HW_PURE_ENHANCED_MODE_STATE = "pure_enhanced_mode_state"

    private const val HW_PURE_MODE = "harmony_os_pure_mode"
    private const val HW_PURE_ENHANCED_MODE = "harmony_os_pure_enhanced_mode"

    private const val SP_USER_IGNORE_GUIDE = "user_ignore_guide"

    private const val SWITCH_EXIST = 1
    private const val SWITCH_ON = 0
    private const val SWITCH_OFF = -1

    private var isThisDeviceUsingEnhancedMode = false // 当前设备是否是增强纯净模式

    fun handlePureModeIfNeeded(
        context: Context,
        gameId: String,
        gameName: String,
        gameType: String,
        callback: () -> Unit
    ) {
        // 用户忽略提醒，不再走下面的逻辑
        if (SPUtils.getBoolean(SP_USER_IGNORE_GUIDE, false)) {
            callback()
            return
        }

        // 仅适用于华为手机
        val manufacturer = android.os.Build.MANUFACTURER
        if (manufacturer != HW) {
            callback.invoke()
            return
        }

        val solidContext = DialogHelper.checkDialogContext(context)

        if (solidContext == null) {
            callback.invoke()
            return
        }

        if (readState(solidContext, HW_PURE_ENHANCED_MODE_STATE) == SWITCH_ON) {
            Utils.log(TAG, "增强纯净模式开启！")
            isThisDeviceUsingEnhancedMode = true

            val pureModeGuide =
                Config.getNewApiSettingsEntity()?.install?.guides?.firstOrNull { it.type == HW_PURE_ENHANCED_MODE }

            if (pureModeGuide != null) {
                showHWHintDialog(solidContext, pureModeGuide, gameId, gameName, gameType, true, callback)
            } else {
                callback.invoke()
            }
        } else if (readState(solidContext, HW_PURE_ENHANCED_MODE_STATE) != SWITCH_EXIST
            && readState(solidContext, HW_PURE_MODE_STATE) == SWITCH_ON
        ) {
            Utils.log(TAG, "纯净模式开启！")
            isThisDeviceUsingEnhancedMode = false

            val pureModeGuide =
                Config.getNewApiSettingsEntity()?.install?.guides?.firstOrNull { it.type == HW_PURE_MODE }

            if (pureModeGuide != null) {
                showHWHintDialog(solidContext, pureModeGuide, gameId, gameName, gameType, false, callback)
            } else {
                callback.invoke()
            }
        } else {
            callback()
        }
    }

    private fun showHWHintDialog(
        context: Context,
        guide: NewApiSettingsEntity.Guide,
        gameId: String,
        gameName: String,
        gameType: String,
        isEnhancedMode: Boolean,
        callback: () -> Unit
    ) {
        var isIgnored = false

        if (context is Activity) {
            if (context.isFinishing) {
                callback.invoke()
                return
            }
        }

        trackDialogShow(isEnhancedMode, gameId, gameName, gameType)

        DialogHelper.showGuideDialog(
            context = context,
            title = guide.title,
            content = guide.content,
            confirmText = guide.buttonTextSettingJump,
            cancelText = guide.buttonTextClose,
            uiModificationCallback = { binding ->
                binding.hintTv.buildSpannableString {
                    addText(guide.linkTextPrefix)
                    addText(guide.linkText) {
                        setColor(ColorResId(com.gh.gamecenter.common.R.color.text_theme))
                        onClick(false) {
                            binding.extraHintIv.performClick()
                        }
                    }
                }
                binding.extraHintIv.setImageResource(R.drawable.ic_home_head_arrow)
                binding.extraHintIv.setOnClickListener {
                    directToLink(
                        context,
                        guide,
                        gameId,
                        gameName,
                        gameType,
                        isEnhancedMode,
                        isIgnored
                    )
                }
                binding.extraHintIv.enlargeTouchArea()
                binding.extraHintIv.visibility = View.VISIBLE
                binding.hintTv.visibility = View.VISIBLE
                binding.selectorContainer.visibility = if (guide.dialogFrequency == "once") View.VISIBLE else View.GONE
                binding.selectorContainer.setOnClickListener {
                    binding.selectorContainer.isChecked = !binding.selectorContainer.isChecked
                    isIgnored = binding.selectorContainer.isChecked
                }

                binding.confirmTv.setOnClickListener {
                    toHWPureModeSetting(context)
                    trackDialogClicked(
                        isEnhancedMode = isEnhancedMode,
                        gameId = gameId,
                        gameName = gameName,
                        gameType = gameType,
                        buttonName = guide.buttonTextSettingJump,
                        isIgnored = isIgnored
                    )
                }

                // 监听是否已授权，授权后自动调起安装并 dismiss dialog
                if (context is AppCompatActivity) {
                    val lifecycle = context.lifecycle
                    lifecycle.addObserver(object : DefaultLifecycleObserver {
                        override fun onResume(owner: LifecycleOwner) {
                            val granted = (isThisDeviceUsingEnhancedMode && readState(context, HW_PURE_ENHANCED_MODE_STATE) != SWITCH_ON)
                                    || (!isThisDeviceUsingEnhancedMode && readState(context, HW_PURE_MODE_STATE) != SWITCH_ON)

                            if (granted) {
                                binding.dialog.dismiss()
                                callback.invoke()
                                lifecycle.removeObserver(this)
                            }
                        }

                        override fun onDestroy(owner: LifecycleOwner) {
                            super.onDestroy(owner)

                            lifecycle.removeObserver(this)
                        }
                    })
                }
            },
            confirmClickCallback = {
                // do nothing, 上面 setOnClickListener 处理了
            },
            cancelClickCallback = {
                if (guide.dialogFrequency == "once" && isIgnored) {
                    SPUtils.setBoolean(SP_USER_IGNORE_GUIDE, true)
                }
                trackDialogClicked(
                    isEnhancedMode = isEnhancedMode,
                    gameId = gameId,
                    gameName = gameName,
                    gameType = gameType,
                    buttonName = guide.buttonTextClose,
                    isIgnored = isIgnored
                )
                callback()
            },
            touchOutsideCallback = {
                if (guide.dialogFrequency == "once" && isIgnored) {
                    SPUtils.setBoolean(SP_USER_IGNORE_GUIDE, true)
                }
                trackDialogClicked(
                    isEnhancedMode = isEnhancedMode,
                    gameId = gameId,
                    gameName = gameName,
                    gameType = gameType,
                    buttonName = "关闭弹窗",
                    isIgnored = isIgnored
                )
                callback()
            },
            extraConfig = DialogHelper.Config(centerTitle = true)
        )
    }

    private fun directToLink(
        context: Context,
        guide: NewApiSettingsEntity.Guide,
        gameId: String,
        gameName: String,
        gameType: String,
        isEnhancedMode: Boolean,
        isIgnored: Boolean
    ) {
        DirectUtils.directToLinkPage(context, guide.link, "纯净模式弹窗", "")
        trackDialogClicked(
            isEnhancedMode,
            gameId,
            gameName,
            gameType,
            "跳转链接",
            isIgnored,
            guide.link.link ?: "",
            guide.link.type ?: "",
            guide.link.text ?: ""
        )
    }

    private fun trackDialogShow(
        isEnhancedMode: Boolean,
        gameId: String,
        gameName: String,
        gameType: String
    ) {
        if (isEnhancedMode) {
            SensorsBridge.trackAddedProtectionDialogShow(
                gameId = gameId,
                gameName = gameName,
                gameType = gameType
            )
        } else {
            SensorsBridge.trackPureModeDialogShow(
                gameId = gameId,
                gameName = gameName,
                gameType = gameType
            )
        }
    }

    private fun trackDialogClicked(
        isEnhancedMode: Boolean,
        gameId: String,
        gameName: String,
        gameType: String,
        buttonName: String,
        isIgnored: Boolean,
        linkId: String? = null,
        linkType: String? = null,
        linkText: String? = null
    ) {
        if (isEnhancedMode) {
            SensorsBridge.trackAddedProtectionDialogClick(
                gameId = gameId,
                gameName = gameName,
                gameType = gameType,
                buttonName = buttonName,
                isIgnored = isIgnored,
                linkId = linkId ?: "",
                linkType = linkType ?: "",
                linkText = linkText ?: ""
            )
        } else {
            SensorsBridge.trackPureModeDialogClick(
                gameId = gameId,
                gameName = gameName,
                gameType = gameType,
                buttonName = buttonName,
                isIgnored = isIgnored,
                linkId = linkId ?: "",
                linkType = linkType ?: "",
                linkText = linkText ?: ""
            )
        }
    }

    private fun toHWPureModeSetting(context: Context) {
        try {
            val intent = Intent()
            intent.setPackage("com.huawei.security.privacycenter")
            intent.setAction("com.huawei.securitycenter.PURE_MODE_ACTIVITY")
            intent.putExtra("intent_from_settings", true)
            context.startActivity(intent)
        } catch (_: Exception) {
            toSystemSettings(context)
        }
    }

    private fun toSystemSettings(context: Context) {
        try {
            val intent = Intent(Settings.ACTION_SETTINGS)
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun readState(context: Context, key: String): Int {
        try {
            val result = Settings.Secure.getInt(context.getContentResolver(), key, SWITCH_OFF)
            Utils.log(TAG, "readState $key state >>> $result")
            return result
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return SWITCH_OFF
    }

}