package com.gh.gamecenter.game.vertical

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.gh.common.databind.BindingAdapters
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.GameSubjectData
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.gh.gamecenter.feature.minigame.MiniGameItemHelper
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.download.DownloadEntity

class GameVerticalAdapter(
    context: Context,
    private var mSubjectEntity: SubjectEntity,
    private var mItemClick: (Int, GameEntity) -> Unit,
    private var mTransparentBackground: Boolean = false
) : BaseRecyclerAdapter<ViewHolder>(context) {

    private val mMaxWidth = mContext.resources.displayMetrics.widthPixels
    private var countAndKey: Pair<Int, String>? = null
    private var mDarkMode = DarkModeUtils.isDarkModeOn(context)

    init {
        var dataIds = ""
        mSubjectEntity.data?.forEach {
            dataIds += it.id
        }
        if (dataIds.isNotEmpty()) countAndKey = Pair(mSubjectEntity.data?.size ?: 0, dataIds)
    }

    fun getIndex(): Int {
        if (mSubjectEntity.data!!.isNotEmpty()) {
            return if (mSubjectEntity.data!![0].image.isNullOrEmpty()) 0 else 1
        }
        return 0
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleGameItemViewHolder {
        return SimpleGameItemViewHolder(GameItemUi(parent.context))
    }

    override fun getItemCount(): Int {
        return mSubjectEntity.data!!.size - getIndex()
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        if (holder is SimpleGameItemViewHolder) {
            if (mTransparentBackground) holder.itemView.setBackgroundColor(com.gh.gamecenter.common.R.color.transparent.toColor())

            val gameEntity = mSubjectEntity.data!![position + getIndex()]
            val subjectData = gameEntity.subjectData!!

            holder.bindSimpleGameItem(
                this@GameVerticalAdapter,
                gameEntity,
                subjectData,
                position,
                mSubjectEntity.list,
                mMaxWidth
            )

            holder.itemView.setOnClickListener {
                mItemClick.invoke(position % mSubjectEntity.list, gameEntity)
            }
        }
    }

    fun checkResetData(updateData: SubjectEntity) {
        var dataIds = ""
        mSubjectEntity = updateData
        mSubjectEntity.data?.forEach {
            dataIds += it.id
        }

        if ((countAndKey?.first == updateData.data?.size && countAndKey?.second != dataIds)
            || mDarkMode != DarkModeUtils.isDarkModeOn(mContext)
        ) {
            // 数量不变,内容发生改变
            notifyItemRangeChanged(0, itemCount)
            mDarkMode = DarkModeUtils.isDarkModeOn(mContext)
        } else if (countAndKey?.first != updateData.data?.size) {
            // 数量发生改变
            notifyDataSetChanged()
        }

        // 重新刷新数据标识
        countAndKey = Pair(updateData.data?.size ?: 0, dataIds)
    }

    fun notifyItemByDownload(downloadEntity: DownloadEntity?) {
        if (downloadEntity == null) {
            notifyDataSetChanged()
        } else {
            for (position in mSubjectEntity.data!!.indices) {
                val entity = mSubjectEntity.data!![position]
                if (downloadEntity.gameId == entity.id) {
                    notifyItemChanged(position - getIndex())
                    return
                }
            }
        }
    }

    fun notifyChildItem(packageName: String) {
        for (position in mSubjectEntity.data!!.indices) {
            val entity = mSubjectEntity.data!![position]
            for (apk in entity.getApk()) {
                if (apk.packageName == packageName) {
                    notifyItemChanged(position - getIndex())
                    return
                }
            }
        }
    }

    class SimpleGameItemViewHolder(private val ui: GameItemUi) : ViewHolder(ui.root) {
        var placeholderGameViewHolder: GameViewHolder? = null

        fun bindSimpleGameItem(
            adapter: RecyclerView.Adapter<ViewHolder>,
            gameEntity: GameEntity,
            subjectData: GameSubjectData? = null,
            position: Int,
            spanCount: Int,
            maxWidth: Int,
            entrance: String = "",
            location: String = ""
        ) {
            val context = itemView.context

            val paddingStart = 16F.dip2px()
            val isEndOfRow = position >= if (adapter.itemCount % spanCount == 0) {
                adapter.itemCount - spanCount
            } else {
                adapter.itemCount - adapter.itemCount % spanCount
            }
            // 你可能会问为什么这下面会有一些，"加1减1" 的魔法。没错，这里的 "加1减1"就是为了规避 bug，做出的一些 UI 补偿
            // bug 的表现可以 checkout https://git.shanqu.cc/android/playground/-/tree/test-snap_adapter_culprit 代码，然后滑动到最后一列体验一下
            var paddingEnd = if (isEndOfRow) 16F.dip2px() else 0F.dip2px()
            val height = 80F.dip2px()

            itemView.layoutParams = if (!isEndOfRow) {
                paddingEnd += 1
                ViewGroup.LayoutParams(maxWidth - 24F.dip2px(), height)
            } else {
                ViewGroup.LayoutParams(maxWidth - 1, height)
            }

            with(ui) {
                gameNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
                serverTypeTv.setTextColor(com.gh.gamecenter.common.R.color.primary_theme.toColor(context))
                downloadTv.background = com.gh.gamecenter.common.R.drawable.download_button_normal_style.toDrawable(context)
                gameDesTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))

                BindingAdapters.setGameName(
                    gameNameTv,
                    gameEntity,
                    false
                )
                BindingAdapters.setGame(iconIv, gameEntity)
                BindingAdapters.setGameTags(gameTagContainer, gameEntity, subjectData?.tag ?: "")
                GameItemViewHolder.initServerType(gameNameTv, serverTypeTv, gameEntity)
                gameDesTv.text = gameEntity.decoratedDes
                GameItemViewHolder.initGameSubtitleAndAdLabel(
                    gameEntity,
                    gameSubtitleTv,
                    gameNameContainer,
                    gameNameTv,
                    gameEntity.adIconActive,
                    adLabelTv
                )

                MiniGameItemHelper.setMiniGameUsage(gamePlayCountTv, gameEntity)

                var gameRatingPaddingEnd = 0
                var gameRatingDrawableStart: Drawable? = null
                var gameRatingTextColor = com.gh.gamecenter.common.R.color.primary_theme.toColor(context)
                var gameRatingText = ""

                gameRatingTv.textSize = if (gameEntity.commentCount > 3) 12F else 10F

                if (gameEntity.commentCount > 3) {
                    gameRatingPaddingEnd = 8F.dip2px()
                    gameRatingDrawableStart = com.gh.gamecenter.feature.R.drawable.game_horizontal_rating.toDrawable()
                    gameRatingTextColor = com.gh.gamecenter.common.R.color.text_theme.toColor(context)
                    gameRatingText =
                        if (gameEntity.star == 10.0F) "10" else gameEntity.star.toString()
                }

                gameRatingTv.setDrawableStart(gameRatingDrawableStart)
                gameRatingTv.setPadding(0, 0, gameRatingPaddingEnd, 0)
                gameRatingTv.setTextColor(gameRatingTextColor)
                gameRatingTv.text = gameRatingText

                // 没错，产品就把这个通用样式叫推荐榜单专题
                downloadTv.putWidgetBusinessName("推荐榜单专题")

                // Fuck this view holder
                val tempViewHolder =
                    placeholderGameViewHolder ?: GameViewHolder(root).apply {
                        placeholderGameViewHolder = this
                    }
                tempViewHolder.gameDes = gameDesTv
                tempViewHolder.gameDownloadBtn = downloadTv
                tempViewHolder.multiVersionDownloadTv = multiVersionDownloadTv
                tempViewHolder.gameDownloadTips = downloadTipsLottie
                tempViewHolder.gameLabelList = gameTagContainer
                tempViewHolder.recommendIv = recommendIv
                tempViewHolder.recommendTv = recommendTv
                tempViewHolder.recommendContainer = recommendConstraintLayout
                tempViewHolder.gameServerType = serverTypeTv

                DownloadItemUtils.updateItem(
                    context,
                    gameEntity,
                    tempViewHolder,
                    subjectData?.briefStyle
                )

                DownloadItemUtils.setOnClickListener(
                    context, downloadTv, gameEntity, position,
                    adapter, entrance, location = location, traceEvent = gameEntity.exposureEvent
                )

                root.setPadding(paddingStart, 8F.dip2px(), paddingEnd, 8F.dip2px())
            }
        }
    }

}