package com.gh.gamecenter.gamedetail.accelerator.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IntDef
import androidx.appcompat.app.AppCompatActivity
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.HaloApp
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.provider.IAcceleratorProvider
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.databinding.DialogFragmentSpeedReplaceGameBinding
import com.therouter.TheRouter

/**
 * 加速器相关的dialog
 */
class AcceleratorDialogFragment : BaseDialogFragment() {

    private lateinit var binding: DialogFragmentSpeedReplaceGameBinding
    private lateinit var uiHelper: SpeedDialogUiHelper
    private var pkgName = ""
    private var gameId = ""
    private var gameName = ""
    private var sourceEntrance = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val type = arguments?.getInt(EntranceConsts.KEY_SPEED_TYPE) ?: 0
        pkgName = arguments?.getString(EntranceConsts.KEY_PACKAGENAME) ?: ""
        gameId = arguments?.getString(EntranceConsts.KEY_GAMEID) ?: ""
        gameName = arguments?.getString(EntranceConsts.KEY_GAMENAME) ?: ""
        sourceEntrance = arguments?.getString(EntranceConsts.KEY_SOURCE_ENTRANCE) ?: ""
        uiHelper = when (type) {
            SPEED_ENABLE_VIP -> {
                SensorsBridge.trackMembershipActivationDialogShow(pkgName, gameId, gameName, sourceEntrance)
                EnableVipUi()
            }

            SPEED_START_FAILURE -> {
                SensorsBridge.trackNetworkAccelerationFailureDialogShow(pkgName, gameId, gameName, sourceEntrance)
                SpeedFailureUi()
            }

            SPEED_STOP -> StopSpeedUi()
            SPEED_NOT_INSTALLED -> NotInstalledUi()
            SPEED_CURRENT_ACCELERATING -> {
                SensorsBridge.trackStopAcceleratingDialogShow(gameId, gameName, pkgName)
                CurrentAcceleratingUi()
            }

            else -> throw IllegalArgumentException("请传递正确的参数 SpeedType !")
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val createDialog = super.onCreateDialog(savedInstanceState)
        createDialog.setCanceledOnTouchOutside(true)
        createDialog.setCancelable(true)
        return createDialog
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return DialogFragmentSpeedReplaceGameBinding.inflate(inflater, container, false)
            .also {
                binding = it
            }.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.tvContent.setText(uiHelper.contentResId)
        binding.tvCancel.goneIf(!uiHelper.isShowCancelButton) {
            if (uiHelper.cancelResId != -1) {
                binding.tvCancel.setText(uiHelper.cancelResId)
            }
            binding.tvCancel.setOnClickListener {
                dismiss()
            }
        }
        binding.tvSubmit.setText(uiHelper.submitResId)
        binding.tvSubmit.setTextColor(uiHelper.submitTextColorResId.toColor(view.context))
        binding.tvSubmit.setBackgroundResource(uiHelper.submitBackgroundResId)

        binding.tvSubmit.setOnClickListener {
            dismiss()
            when (uiHelper) {

                is EnableVipUi -> {
                    SensorsBridge.trackMembershipActivationDialogClick(
                        pkgName,
                        gameId,
                        gameName,
                        sourceEntrance
                    )
                    SensorsBridge.trackMyAssetsPageShow(pkgName, gameId, gameName, sourceEntrance)
                    DirectUtils.navigateToMyAssetsPage(requireContext(), sourceEntrance)
                }

                is SpeedFailureUi -> {
                    SensorsBridge.trackNetworkAccelerationFailureDialogClick(pkgName, gameId, gameName, sourceEntrance)
                    context?.let {
                        DirectUtils.directToWebView(it, Constants.QQ_QIDIAN_ADDRESS, "")
                    }
                }

                is StopSpeedUi, is CurrentAcceleratingUi -> {
                    TheRouter.get(IAcceleratorProvider::class.java)?.stopQyGameAccelerate()
                }

            }
        }
    }

    override fun onStart() {
        super.onStart()
        val width = HaloApp.getInstance().resources.displayMetrics.widthPixels - 60F.dip2px()
        val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    companion object {

        const val SPEED_ENABLE_VIP = 1
        const val SPEED_START_FAILURE = 2
        const val SPEED_STOP = 3
        const val SPEED_NOT_INSTALLED = 4
        const val SPEED_CURRENT_ACCELERATING = 5

        fun show(
            @SpeedType type: Int,
            pkgName: String,
            gameId: String,
            gameName: String,
            sourceEntrance: String,
            context: Context
        ) {
            if (context is AppCompatActivity) {
                context.supportFragmentManager
            } else {
                (CurrentActivityHolder.getCurrentActivity() as? AppCompatActivity)?.supportFragmentManager
            }?.let {
                val fragment = AcceleratorDialogFragment().apply {
                    arguments = Bundle().apply {
                        putInt(EntranceConsts.KEY_SPEED_TYPE, type)
                        putString(EntranceConsts.KEY_PACKAGENAME, pkgName)
                        putString(EntranceConsts.KEY_GAMEID, gameId)
                        putString(EntranceConsts.KEY_GAMENAME, gameName)
                        putString(EntranceConsts.KEY_SOURCE_ENTRANCE, sourceEntrance)
                    }
                }
                fragment.show(it, AcceleratorDialogFragment::class.java.simpleName)
            }

        }
    }

    @IntDef(SPEED_ENABLE_VIP, SPEED_START_FAILURE, SPEED_STOP, SPEED_NOT_INSTALLED, SPEED_CURRENT_ACCELERATING)
    @Retention(AnnotationRetention.SOURCE)
    annotation class SpeedType

    abstract class SpeedDialogUiHelper {

        abstract val contentResId: Int

        abstract val isShowCancelButton: Boolean

        open val cancelResId: Int = -1

        abstract val submitResId: Int

        open val submitTextColorResId = com.gh.gamecenter.common.R.color.text_aw_primary

        open val submitBackgroundResId = com.gh.gamecenter.common.R.drawable.bg_common_button_fill_blue
    }

    class EnableVipUi : SpeedDialogUiHelper() {
        override val contentResId: Int
            get() = R.string.enable_vip_tips

        override val isShowCancelButton: Boolean
            get() = false

        override val submitResId: Int
            get() = R.string.go_to_activate

    }

    class SpeedFailureUi : SpeedDialogUiHelper() {
        override val contentResId: Int
            get() = R.string.speed_failure_tips

        override val isShowCancelButton: Boolean
            get() = false

        override val submitResId: Int
            get() = R.string.contact_service

        override val submitTextColorResId: Int
            get() = com.gh.gamecenter.common.R.color.primary_theme

        override val submitBackgroundResId: Int
            get() = com.gh.gamecenter.common.R.drawable.bg_common_button_light_fill_blue

    }

    class StopSpeedUi : SpeedDialogUiHelper() {
        override val contentResId: Int
            get() = R.string.stop_speed_tips

        override val isShowCancelButton: Boolean
            get() = true

        override val submitResId: Int
            get() = R.string.stop_speed

        override val cancelResId: Int
            get() = R.string.cancel

    }

    class NotInstalledUi : SpeedDialogUiHelper() {

        override val contentResId: Int
            get() = R.string.speed_not_installed_tips

        override val isShowCancelButton: Boolean
            get() = false

        override val submitResId: Int
            get() = R.string.dialog_hint_confirm
    }

    class CurrentAcceleratingUi : SpeedDialogUiHelper() {
        override val contentResId: Int
            get() = R.string.speed_current_game_accelerating

        override val isShowCancelButton: Boolean
            get() = true

        override val submitResId: Int
            get() = R.string.stop_speed

        override val cancelResId: Int
            get() = R.string.cancel

    }
}