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

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.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.game.vertical.GameItemUi
import com.gh.gamecenter.home.custom.eventlistener.GameSubjectCollectionEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageData
import com.gh.gamecenter.home.custom.model.CustomSubjectCollectionItem
import com.lightgame.download.DownloadEntity

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

    private val mMaxWidth = context.resources.displayMetrics.widthPixels

    private var _spanCount: Int = 3
    private lateinit var _data: CustomSubjectCollectionItem
    private lateinit var _subject: CustomPageData.LinkColumnCollection.CustomSubjectEntity

    fun setData(
        spanCount: Int,
        data: CustomSubjectCollectionItem,
        subject: CustomPageData.LinkColumnCollection.CustomSubjectEntity
    ) {
        _spanCount = spanCount
        _data = data
        _subject = subject
        submitList(subject.games)
    }

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

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

    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,
                _spanCount,
                mMaxWidth,
                eventHelper = eventHelper
            )

            holder.itemView.setOnClickListener {
                eventHelper.navigateToGameDetailPage(position % 3, gameEntity, _subject)
            }
        }
    }

    override fun notifyDownload(download: DownloadEntity) {
        super.notifyDownload(download)
    }

    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
            }
        }
    }

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

        private var exposureEvent: ExposureEvent? = null

        fun bindSimpleGameItem(
            adapter: RecyclerView.Adapter<ViewHolder>,
            gameEntity: GameEntity,
            position: Int,
            spanCount: Int,
            maxWidth: Int,
            entrance: String = "",
            location: String = "",
            eventHelper: GameSubjectCollectionEventHelper
        ) {
            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()

            exposureEvent = gameEntity.exposureEvent

            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.setGameTagsWithSellingPoint(gameTagContainer, sellingPointsBinding, gameEntity, "")
                GameItemViewHolder.initServerType(gameNameTv, serverTypeTv, gameEntity)
                gameDesTv.text = gameEntity.decoratedDes
                GameItemViewHolder.initGameSubtitleAndAdLabel(
                    gameEntity,
                    gameSubtitleTv,
                    gameNameContainer,
                    gameNameTv,
                    gameEntity.adIconActive,
                    adLabelTv
                )

                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("推荐榜单专题")

                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
                )

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

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

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