package com.gh.gamecenter.gamedetail.dialog

import android.content.Context
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.gh.common.util.DetailDownloadUtils
import com.gh.common.util.DirectUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.DetailViewHolder
import com.gh.gamecenter.common.base.fragment.BaseBottomDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.databinding.DialogFragmentDspGameDetailBinding
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.feature.entity.GameEntity
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

class DspGameDetailDialogFragment : BaseBottomDialogFragment<DialogFragmentDspGameDetailBinding>() {

    private var gameEntity: GameEntity? = null

    private val dataWatcher = object : DataWatcher() {
        override fun onDataChanged(downloadEntity: DownloadEntity) {
            updateDownloadStatus()
        }

        override fun onDataInit(downloadEntity: DownloadEntity) {
            updateDownloadStatus()
        }
    }

    private fun updateDownloadStatus() {
        gameEntity?.let {
            DetailDownloadUtils.updateViewHolder(
                DetailViewHolder(
                    mBinding.detailLlBottom,
                    null,
                    it,
                    false,
                    "",
                    "",
                    "",
                    null,
                    false,
                    null,
                    null
                )
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        gameEntity = arguments?.getParcelable(EntranceConsts.KEY_GAME_ENTITY)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        gameEntity?.let {
            val apk = it.getApk().firstOrNull()

            mBinding.ivIcon.displayGameIcon(it)
            mBinding.tvName.text = it.name
            mBinding.tvVersion.text = getString(R.string.version_name, apk?.version ?: "")
            mBinding.titleView.setOnRightClickListener { dismiss() }
            mBinding.tvDeveloper.text = getString(R.string.developer_name, it.developer ?: "")

            mBinding.tvPermissions.setOnClickListener {
                logClickEvent("游戏详情-应用权限")
                DirectUtils.directToWebView(
                    context = requireContext(),
                    url = gameEntity?.permissionsUrl ?: "",
                    title = "应用权限")
            }

            mBinding.tvPrivacyPolicy.setOnClickListener {
                logClickEvent("游戏详情-隐私政策")
                DirectUtils.directToWebView(
                    context = requireContext(),
                    url = gameEntity?.privacyUrl ?: "",
                    title = "隐私政策"
                )
            }

            mBinding.detailProgressbar.goneIf(apk == null)
            if (apk != null) {
                mBinding.detailProgressbar.setOnTouchListener { _, motionEvent ->
                    if (motionEvent.action == MotionEvent.ACTION_DOWN) {
                        logClickEvent("游戏详情-按钮")
                    }
                    return@setOnTouchListener false
                }

                DetailDownloadUtils.updateViewHolder(
                    DetailViewHolder(
                        mBinding.detailLlBottom,
                        null,
                        it,
                        false,
                        "",
                        "",
                        "",
                        null,
                        false,
                        null
                    )
                )
            }
        }
    }

    override fun onResume() {
        super.onResume()
        DownloadManager.getInstance().addObserver(dataWatcher)
    }

    override fun onPause() {
        super.onPause()
        DownloadManager.getInstance().removeObserver(dataWatcher)
    }

    override fun onDestroyView() {
        super.onDestroyView()

        logClickEvent("游戏详情-关闭弹窗")
    }

    private fun logClickEvent(text: String) {
        gameEntity?.let {
            val dspLogMap = it.tempDspLogMap as? HashMap<String, String>

            dspLogMap?.let {
                dspLogMap["text"] = text
                SensorsBridge.trackDspAdClick(JSONObject(dspLogMap as Map<*, *>?))
            }
        }
    }

    // 接受安装、卸载消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(busFour: EBPackage) {
        if (gameEntity != null && gameEntity!!.getApk().size > 0) {
            for (apk in gameEntity!!.getApk()) {
                if (busFour.packageName == apk.packageName) {
                    updateDownloadStatus()
                }
            }
        }
    }

    companion object {
        fun show(context: Context, gameEntity: GameEntity) {
            if (context is AppCompatActivity) {
                context.supportFragmentManager
            } else {
                (CurrentActivityHolder.getCurrentActivity() as? AppCompatActivity)?.supportFragmentManager
            }?.let {
                val fragment = DspGameDetailDialogFragment().apply {
                    arguments = Bundle().apply {
                        putParcelable(EntranceConsts.KEY_GAME_ENTITY, gameEntity)
                    }
                }
                fragment.show(it, fragment::class.java.simpleName)
            }
        }
    }
}