package com.gh.gamecenter.simulatorgame

import android.content.Context
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.recyclerview.widget.RecyclerView
import com.g00fy2.versioncompare.Version
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.common.simulator.SimulatorDownloadManager
import com.gh.common.util.*
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.databinding.SimulatorItemBinding
import com.gh.gamecenter.entity.SimulatorEntity

class SimulatorManagementAdapter(
    context: Context,
    var fragment: SimulatorManagementFragment
) : ListAdapter<SimulatorEntity>(context) {

    private var mSingleSelectedPosition = -1
    private var mSingleSelectFlag = false
    private var mShowSelectFlag = false
    private var mSelectList = ArrayList<Boolean>()
    private var mPopWindow: PopupWindow? = null

    override fun setListData(updateData: MutableList<SimulatorEntity>?) {
        mSelectList.clear()
        updateData?.forEach { _ ->
            mSelectList.add(false)
        }
        super.setListData(updateData)
    }

    override fun getItemCount() = mEntityList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        SimulatorManagementViewHolder(parent.toBinding())

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is SimulatorManagementViewHolder -> {
                val simulator = mEntityList[position]
                val isInstalled = PackageUtils.isInstalledFromAllPackage(mContext, simulator.apk?.packageName)

                holder.binding.simulatorInstallBtn.run {
                    holder.binding.simulatorName.text = simulator.name
                    var shouldShowUpdate = false

                    if (isInstalled) {
//                        val versionFromInstalledApp = PackageUtils.getVersionNameByPackageName(simulator.apk?.packageName)
                        shouldShowUpdate = PackageUtils.isInstalledApkMatchedMd5(simulator.apk?.packageName, simulator.apk?.md5)
                        text = if (shouldShowUpdate) "更新" else "卸载"
                        setTextColor(if (shouldShowUpdate) R.color.theme.toColor(mContext) else R.color.text_subtitleDesc.toColor(mContext))
                    } else {
                        text = "安装"
                        setTextColor(R.color.theme.toColor(mContext))
                    }

                    setOnClickListener {
                        NewFlatLogUtils.logSimulatorListClick(text.toString(), simulator.type)
                        if (isInstalled) {
                            if (shouldShowUpdate) {
                                SimulatorDownloadManager.getInstance().showDownloadDialog(
                                    context,
                                    simulator,
                                    SimulatorDownloadManager.SimulatorLocation.SIMULATOR_MANAGE
                                )
                            } else {
                                holder.itemView.performClick()
                            }
                        } else {
                            SimulatorDownloadManager.getInstance().showDownloadDialog(
                                mContext,
                                simulator,
                                SimulatorDownloadManager.SimulatorLocation.SIMULATOR_MANAGE
                            )
                        }
                    }
                }

                holder.binding.selectIv.run {
                    goneIf(!mShowSelectFlag)
                    setImageResource(
                        when {
                            mSelectList[position] && isInstalled -> R.drawable.ic_simulator_selected

                            !mSelectList[position] && isInstalled -> R.drawable.ic_simulator_unselect

                            else -> {
                                mSelectList[position] = false
                                R.drawable.ic_simulator_unable
                            }
                        }
                    )
                    setOnClickListener {
                        if (isInstalled) {
                            setImageResource(
                                if (mSelectList[position])
                                    R.drawable.ic_simulator_unselect
                                else
                                    R.drawable.ic_simulator_selected
                            )
                            mSelectList[position] = !mSelectList[position]
                        }
                    }
                }

                if (mSingleSelectFlag && position == mSingleSelectedPosition) {
                    holder.binding.container.setBackgroundColor(R.color.bg_F6FBFF.toColor(mContext))
                } else {
                    holder.binding.container.setBackgroundColor(R.color.background_white.toColor(mContext))
                }

                holder.itemView.setOnClickListener {
                    if (isInstalled && !mShowSelectFlag) {
//                        showUnInstallWindow(position)
                        showUnInstallSimulatorAlert(position)
                    }
                }
            }
        }
    }

    private fun showUnInstallSimulatorAlert(position: Int = -1){
        val simulator = mEntityList[position]
        NewFlatLogUtils.logSimulatorUninstallAlertShow(simulator.type)
        DialogHelper.showDialog(
            mContext,
            "提示",
            "卸载模拟器可能会导致对应游戏的本地存档数据丢失，请确认后操作",
            "再等等",
            "卸载",
            confirmClickCallback = { NewFlatLogUtils.logSimulatorUninstallAlertClick("再等等") },
            cancelClickCallback = {
                unInstallSimulator()
                NewFlatLogUtils.logSimulatorUninstallAlertClick("卸载")
            },
            uiModificationCallback = { binding ->
                binding.cancelTv.setTextColor(R.color.theme_red.toColor(mContext))
                binding.confirmTv.setTextColor(R.color.text_subtitle.toColor(mContext))
                binding.contentTv.setTextColor(R.color.text_subtitle.toColor(mContext))
            },
            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
        if (!mShowSelectFlag) mSingleSelectFlag = true
        if (!mShowSelectFlag) {
            if (mSingleSelectFlag) {
                mSingleSelectedPosition = position
            }

            if (mSingleSelectedPosition != -1) {
                notifyItemChanged(mSingleSelectedPosition)
            }
        }
    }

    private fun showUnInstallWindow(position: Int = -1) {
        if (mPopWindow != null && mPopWindow!!.isShowing) {
            if (!mShowSelectFlag) mSingleSelectFlag = false
            mPopWindow?.dismiss()
        } else if (mPopWindow != null) {
            if (!mShowSelectFlag) mSingleSelectFlag = true
            mPopWindow?.showAtLocation(fragment.requireActivity().window.decorView, Gravity.BOTTOM, 0, 0)
        } else {
            if (!mShowSelectFlag) mSingleSelectFlag = true
            val contentView = View.inflate(mContext, R.layout.popup_simulator_uninstall, null)
            contentView.isFocusable = true
            contentView.isFocusableInTouchMode = true
            val unInstallBtn = contentView.findViewById<LinearLayout>(R.id.unInstallBtn)

            mPopWindow =
                PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            mPopWindow?.showAtLocation(fragment.requireActivity().window.decorView, Gravity.BOTTOM, 0, 0)

            unInstallBtn.setOnClickListener {
                if (mShowSelectFlag && !mSelectList.contains(true)) {
                    ToastUtils.showToast("请选择模拟器")
                } else {
                    DialogHelper.showDialog(
                        mContext,
                        "提示",
                        "卸载模拟器可能会导致对应游戏的本地存档数据丢失，请确认后操作",
                        "再等等",
                        "卸载",
                        cancelClickCallback = { unInstallSimulator() },
                        uiModificationCallback = { binding ->
                            binding.cancelTv.setTextColor(R.color.theme_red.toColor(mContext))
                            binding.confirmTv.setTextColor(R.color.text_subtitle.toColor(mContext))
                            binding.contentTv.setTextColor(R.color.text_subtitle.toColor(mContext))
                        },
                        extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                    )
                }
            }
        }

        if (!mShowSelectFlag) {
            if (mSingleSelectFlag) {
                mSingleSelectedPosition = position
            }

            if (mSingleSelectedPosition != -1) {
                notifyItemChanged(mSingleSelectedPosition)
            }
        }
    }

    private fun unInstallSimulator() {
        if (mShowSelectFlag) {
            mSelectList.forEachIndexed { index, b ->
                if (b) {
                    val simulator = mEntityList[index]
                    PackageInstaller.uninstallForPackageName(mContext, simulator.apk?.packageName ?: "")
                }
            }
        } else {
            val simulator = mEntityList[mSingleSelectedPosition]
            PackageInstaller.uninstallForPackageName(mContext, simulator.apk?.packageName ?: "")
            dismissPopWindow()
        }

    }

    fun showUnInstallWindowAndSelectIv(show: Boolean, isFromUpdate: Boolean? = false) {
        mShowSelectFlag = show
        mSingleSelectFlag = false
        mSingleSelectedPosition = -1
        if (isFromUpdate == false) {
            for (i in 0 until mSelectList.size) {
                mSelectList[i] = false
            }
        }
        notifyDataSetChanged()
        dismissPopWindow(true)
        if (show) showUnInstallWindow()
    }

    fun dismissPopWindow(isForce: Boolean = false) {
        if (!isForce && mShowSelectFlag) return

        if (mPopWindow != null && mPopWindow!!.isShowing) {
            mSingleSelectFlag = false
            mPopWindow?.dismiss()
        }

        if (mSingleSelectedPosition != -1) {
            notifyItemChanged(mSingleSelectedPosition)
        }
    }

    fun updatePopupWindow() {
        if (mPopWindow != null && mPopWindow!!.isShowing) {
            mPopWindow?.dismiss()
            mPopWindow = null
            if (mShowSelectFlag) {
                showUnInstallWindowAndSelectIv(show = true, isFromUpdate = true)
            } else {
                showUnInstallWindow(mSingleSelectedPosition)
            }
        }
    }

    inner class SimulatorManagementViewHolder(val binding: SimulatorItemBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)
}