package com.gh.gamecenter.gamedetail.history

import android.content.Context
import android.util.SparseBooleanArray
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.recyclerview.widget.RecyclerView
import com.g00fy2.versioncompare.Version
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureSource
import com.gh.common.exposure.IExposable
import com.gh.common.util.*
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.common.xapk.XapkInstaller
import com.gh.common.xapk.XapkUnzipStatus
import com.gh.download.DownloadManager
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.TimeUtils
import com.gh.gamecenter.common.utils.getMetaExtra
import com.gh.gamecenter.common.utils.setRootBackgroundColor
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.databinding.ItemHistoryApkBinding
import com.gh.gamecenter.feature.entity.ApkEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.manager.PackagesManager
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus
import com.lightgame.utils.Utils

class HistoryApkListAdapter(
    context: Context,
    private var mViewModel: HistoryApkListViewModel,
    private var mEntrance: String
) : ListAdapter<GameEntity>(context), IExposable {

    private val mBasicExposureSource by lazy { ExposureSource("历史版本", "") }

    private var mExpandSparseBooleanArray = SparseBooleanArray()
    private var mDescExpandedMarginRight = -1
    private var mDescShrankMarginRight = -1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view: View
        return when (viewType) {
            ItemViewType.ITEM_BODY -> {
                view = mLayoutInflater.inflate(R.layout.item_history_apk, parent, false)
                HistoryApkViewHolder(ItemHistoryApkBinding.bind(view))
            }
            else -> throw IllegalAccessException("No viewType is matched.")
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is HistoryApkViewHolder -> {
                val gameEntity = mEntityList[position]
                val apkEntity = gameEntity.getApk().first()
                val maxDesLines = if (mExpandSparseBooleanArray.get(holder.adapterPosition)) Int.MAX_VALUE else 3

                val exposureEvent =
                    ExposureEvent.createEvent(gameEntity = gameEntity, source = listOf(mBasicExposureSource))

                holder.binding.root.setRootBackgroundColor(R.color.background_white)
                holder.binding.updateDescTv.text = apkEntity.updateDesc
                holder.binding.versionTv.text = "版本${apkEntity.version}"
                holder.binding.updateDescTv.setExpandMaxLines(maxDesLines)
                holder.binding.updateDescTv.setIsExpanded(maxDesLines == Int.MAX_VALUE)
                holder.binding.releaseDateTv.text = TimeUtils.getFormatTime(apkEntity.updateTime)
                holder.binding.updateDescTv.setExpandCallback {
                    mExpandSparseBooleanArray.put(holder.adapterPosition, true)
                    updateDescMarginRight(
                        holder.binding.updateDescTv,
                        mExpandSparseBooleanArray.get(holder.adapterPosition),
                        holder.binding.downloadBtn.visibility == View.VISIBLE
                    )
                    MtaHelper.onEvent("历史版本", "展开", "${mViewModel.game?.name}+${apkEntity.version}")
                }
                holder.binding.downloadBtn.run {
                    setOnTouchListener { _, event ->
                        if (event.action == MotionEvent.ACTION_UP) {
                            if (souldShowDowngradeDialog(apkEntity, text)) {
                                DialogHelper.showDowngradeHintDialog(mContext) {
                                    performClick()
                                }
                                return@setOnTouchListener true
                            }
                            return@setOnTouchListener false
                        }
                        return@setOnTouchListener false
                    }

                    DownloadItemUtils.setOnClickListener(
                        holder.binding.root.context,
                        this,
                        gameEntity,
                        0,
                        this@HistoryApkListAdapter,
                        "$mEntrance+(历史版本)",
                        "历史版本",
                        exposureEvent
                    )

                    if (apkEntity.downloadStatus == "off" || apkEntity.url.isNullOrEmpty()) {
                        visibility = View.INVISIBLE
                    } else if (gameEntity.getApk().size == 1) {
                        visibility = View.VISIBLE
                        var downloadText = ""
                        val downloadEntity = DownloadManager.getInstance().getDownloadEntityByUrl(apkEntity.url)
                        if (downloadEntity != null) {
                            val xapkStatus = downloadEntity.meta[XapkInstaller.XAPK_UNZIP_STATUS]
                            downloadText = if (XapkUnzipStatus.UNZIPPING.name == xapkStatus) {
                                resources.getString(R.string.unzipping)
                            } else if (downloadEntity.status == DownloadStatus.done) {
                                if (PackagesManager.isInstalledWithSpecificVersion(
                                        downloadEntity.packageName,
                                        downloadEntity.versionName
                                    )
                                ) {
                                    resources.getString(R.string.launch)
                                } else {
                                    resources.getString(R.string.install)
                                }
                            } else {
                                if (downloadEntity.status == DownloadStatus.waiting) {
                                    resources.getString(R.string.waiting)
                                } else {
                                    resources.getString(R.string.downloading)
                                }
                            }
                        } else {
                            downloadText = if (PackagesManager.isInstalledWithSpecificVersion(
                                    apkEntity.packageName, apkEntity.version
                                        ?: ""
                                )
                            ) {
                                resources.getString(R.string.launch)
                            } else {
                                resources.getString(R.string.download)
                            }
                        }

                        buttonStyle = if ("下载中" == downloadText) {
                            DownloadButton.ButtonStyle.DOWNLOADING_NORMAL
                        } else {
                            DownloadButton.ButtonStyle.NORMAL
                        }

                        text = downloadText
                    }
                }
                updateDescMarginRight(
                    holder.binding.updateDescTv,
                    mExpandSparseBooleanArray.get(holder.adapterPosition),
                    holder.binding.downloadBtn.visibility == View.VISIBLE
                )
            }
        }
    }

    // damn, 设计师说要存在下载按钮和不存在下载按钮时有不一样的收起/展开效果
    private fun updateDescMarginRight(descTv: TextView, isExpanded: Boolean, isDownloadBtnVisible: Boolean) {
        if (mDescExpandedMarginRight == -1) {
            mDescExpandedMarginRight = 0
            mDescShrankMarginRight =
                mContext.resources.getDimension(R.dimen.history_apk_desc_shrank_margin_right).toInt()
        }

        val constraintSet = ConstraintSet()
        constraintSet.clone(descTv.parent as ConstraintLayout)

        if (!isDownloadBtnVisible || isExpanded) {
            constraintSet.setMargin(descTv.id, ConstraintSet.RIGHT, mDescExpandedMarginRight)
        } else {
            constraintSet.setMargin(descTv.id, ConstraintSet.RIGHT, mDescShrankMarginRight)
        }
        constraintSet.applyTo(descTv.parent as ConstraintLayout)
    }

    private fun souldShowDowngradeDialog(apkEntity: ApkEntity, btnText: CharSequence): Boolean {
        when (btnText) {
            "下载" -> MtaHelper.onEvent("历史版本", "下载", "${mViewModel.game?.name}_${apkEntity.version}")
            "下载中" -> MtaHelper.onEvent("历史版本", "下载中", "${mViewModel.game?.name}_${apkEntity.version}")
            "安装" -> MtaHelper.onEvent("历史版本", "安装", "${mViewModel.game?.name}_${apkEntity.version}")
            "启动" -> MtaHelper.onEvent("历史版本", "启动", "${mViewModel.game?.name}_${apkEntity.version}")
        }
        if (btnText == "安装" || btnText == "下载") {
            if (PackageUtils.isInstalled(mContext, apkEntity.packageName)) {
                val installedVersion = PackageUtils.getVersionNameByPackageName(apkEntity.packageName)
                if (Version(installedVersion).isHigherThan(Version(apkEntity.version))) {
                    return true
                }
            }
        }
        return false
    }

    override fun areItemsTheSame(oldItem: GameEntity?, newItem: GameEntity?): Boolean {
        return oldItem?.id == newItem?.id
    }

    override fun areContentsTheSame(oldItem: GameEntity?, newItem: GameEntity?): Boolean {
        return oldItem?.id == newItem?.id
    }

    override fun getItemViewType(position: Int): Int {
        return ItemViewType.ITEM_BODY
    }

    override fun getItemCount(): Int {
        return if (mEntityList.isNullOrEmpty()) 0 else mEntityList.size
    }

    fun notifyItemByDownload(downloadEntity: DownloadEntity?) {
        if (downloadEntity == null) {
            notifyDataSetChanged()
            Utils.log("下载状态" + downloadEntity?.status)
        } else {
            for (position in mEntityList.indices) {
                val gameEntity = mEntityList[position]
                if (downloadEntity.getMetaExtra("gameId") == gameEntity.id) {
                    notifyItemChanged(position)
                    Utils.log("下载状态" + downloadEntity.status)
                }
            }
        }
    }

    override fun getEventByPosition(pos: Int) = mEntityList[pos].exposureEvent

    override fun getEventListByPosition(pos: Int) = null

    class HistoryApkViewHolder(var binding: ItemHistoryApkBinding) : RecyclerView.ViewHolder(binding.root)
}