package com.gh.gamecenter.home.custom.adapter

import android.content.Context
import android.os.Build
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.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.IExposureProvider
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.gh.gamecenter.feature.minigame.MiniGameItemHelper
import com.gh.gamecenter.game.vertical.GameItemUi
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.lightgame.download.DownloadEntity

class CustomGameVerticalAdapter(
    context: Context,
    private var mTransparentBackground: Boolean = false,
    private val eventHelper: SubjectEventHelper,
) : CustomBaseChildAdapter<GameEntity, ViewHolder>(context) {

    private val mMaxWidth = context.resources.displayMetrics.widthPixels

    private lateinit var _data: SubjectEntity

    fun setData(data: SubjectEntity) {
        _data = data
        submitList(data.data)
    }

    override fun getKey(t: GameEntity): String {
        return t.id
    }

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

    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 = dataList[position]

            holder.bindSimpleGameItem(
                this,
                gameEntity,
                position,
                _data.list,
                mMaxWidth,
                briefStyle = _data.briefStyle,
                adIconActive = _data.adIconActive,
                showSubscript = _data.showIndexIconSubscript,
                showSubTitle = _data.showIndexSubtitle,
                subjectTag = _data.tag ?: ""
            )

            holder.itemView.setOnClickListener {
                val childPosition = position % _data.list
                eventHelper.navigateToGameDetailPage(childPosition, gameEntity)
            }
        }
    }

    override fun notifyDownload(download: DownloadEntity) {
        dataList.forEachIndexed { index, item ->
            if (item.id == download.gameId) {
                notifyItemChanged(index)
                return
            }
        }
    }

    override fun notifyDownloadDeleted(status: EBDownloadStatus) {
        notifyChildItem(status.packageName)
    }

    override fun notifyInstalled(busFour: EBPackage) {
        notifyChildItem(busFour.packageName)
    }

    private fun notifyChildItem(packageName: String) {
        dataList.forEachIndexed { position, game ->
            val hasSamePackageName = game.getApk().any {
                it.packageName == packageName
            }
            if (hasSamePackageName) {
                notifyItemChanged(position)
                return
            }
        }

    }

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

        private var boundedGameEntity: GameEntity? = null

        fun bindSimpleGameItem(
            adapter: RecyclerView.Adapter<ViewHolder>,
            gameEntity: GameEntity,
            position: Int,
            spanCount: Int,
            maxWidth: Int,
            entrance: String = "",
            location: String = "",
            briefStyle: String,
            adIconActive: Boolean,
            showSubscript: Boolean,
            showSubTitle: Boolean,
            subjectTag: String = ""
        ) {
            val context = itemView.context

            boundedGameEntity = gameEntity

            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
                )
                iconIv.displayGameIconWithIfShowSubscript(gameEntity, showSubscript)
                BindingAdapters.setGameTagsWithSellingPoint(
                    gameTagContainer,
                    sellingPointsBinding,
                    gameEntity,
                    subjectTag
                )
                GameItemViewHolder.initServerType(gameNameTv, serverTypeTv, gameEntity)

                val styleResId = R.style.CustomPageGameRating
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    gameRatingTv.setTextAppearance(styleResId)
                } else {
                    gameRatingTv.setTextAppearance(context, styleResId)
                }
                gameRatingTv.setPadding(0, 0, 8f.dip2px(), 0)
                gameRatingTv.setDrawableStart(com.gh.gamecenter.feature.R.drawable.game_horizontal_rating)
                CustomViewExt.setGameRatting(gameRatingTv, briefStyle, gameEntity)
                CustomViewExt.setDescription(gameDesTv, briefStyle, gameEntity)
                GameItemViewHolder.initGameSubtitleAndAdLabelOnGameSubject(
                    gameEntity,
                    gameSubtitleTv,
                    gameNameContainer,
                    gameNameTv,
                    adIconActive,
                    adLabelTv,
                    showSubTitle
                )

                MiniGameItemHelper.setMiniGameUsage(gamePlayCountTv, gameEntity)

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

                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,
                    briefStyle
                )

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

                root.setPadding(paddingStart, root.paddingTop, paddingEnd, root.paddingBottom)
            }
        }

        override fun provideExposureData(): ExposureEvent? {
            return boundedGameEntity?.exposureEvent?.getFreshExposureEvent()
        }
    }

}