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

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.databinding.RecyclerChildIconMatrixCustomBinding
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.home.custom.adapter.CustomPageAdapter.Companion.PAYLOAD_REFRESH_GAME_CHANGED
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.gh.gamecenter.home.custom.model.CustomSplitSubjectItem
import com.lightgame.download.DownloadEntity

class CustomIconMatrixAdapter(
    context: Context,
    private val eventHelper: SubjectEventHelper
) : CustomBaseChildAdapter<GameEntity, CustomIconMatrixAdapter.CustomChildIconMatrixViewHolder>(context) {

    private var _data: CustomSplitSubjectItem? = null

    private var _exposureEventList: List<ExposureEvent>? = null

    fun setData(data: CustomSplitSubjectItem, exposureEventList: List<ExposureEvent>) {
        _data = data
        _exposureEventList = exposureEventList
        val list = arrayListOf<GameEntity>()
        for (index in data.startChildPosition..data.endChildPosition) {
            data.data.data?.getOrNull(index)?.let(list::add)
        }
        submitList(list)
    }

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

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

    override fun onBindViewHolder(holder: CustomChildIconMatrixViewHolder, position: Int, payloads: MutableList<Any>) {
        val isRefreshDownloadStatus = payloads.any {
            PAYLOAD_REFRESH_GAME_CHANGED == it
        }

        holder.boundedGameEntity = getItem(position)

        if (isRefreshDownloadStatus) {
            DownloadItemUtils.updateItem(
                context,
                getItem(position),
                GameViewHolder(holder.binding.simpleGameContainer.root).apply {
                    gameDownloadBtn = holder.binding.simpleGameContainer.downloadBtn
                    gameDownloadTips = holder.binding.simpleGameContainer.downloadTipsLottie
                    multiVersionDownloadTv = holder.binding.simpleGameContainer.multiVersionDownloadTv
                },
            )
        } else {
            super.onBindViewHolder(holder, position, payloads)
        }
    }

    override fun onBindViewHolder(holder: CustomChildIconMatrixViewHolder, position: Int) {
        _data?.data?.let { subject ->
            holder.itemView.visibleIf(true)
            val item = getItem(position)
            with(holder.binding.simpleGameContainer) {
                gameIcon.displayGameIconWithIfShowSubscript(item, subject.showIndexIconSubscript)
                downloadBtn.goneIf(!subject.showDownload)
                com.gh.gamecenter.game.horizontal.GameHorizontalSimpleItemViewHolder.setHorizontalNameAndGravity(
                    gameName,
                    item.name
                )
                gameName.maxLines = if (subject.showDownload) 1 else 2
            }
            val showStar = subject.showStar
                    && subject.data?.any { it.commentCount > 3 } ?: false
            CustomViewExt.setGameRattingWithSubject(holder.binding.gameRating, showStar, item)
            val entranceResult =
                StringUtils.buildString("(游戏-专题:", subject.name, "-列表[", (position + 1).toString(), "])")
            val locationResult = StringUtils.buildString("游戏-专题-", subject.name, ":", item.name)

            if (subject.showDownload) {
                DownloadItemUtils.setOnClickListener(
                    context,
                    holder.binding.simpleGameContainer.downloadBtn,
                    item,
                    position,
                    this,
                    entranceResult,
                    location = locationResult,
                    traceEvent = _exposureEventList?.getOrNull(position)
                ) {
                    eventHelper.onDownloadButtonClick(position, item)
                }

                DownloadItemUtils.updateItem(
                    context,
                    item,
                    GameViewHolder(holder.binding.simpleGameContainer.root).apply {
                        gameDownloadBtn = holder.binding.simpleGameContainer.downloadBtn
                        gameDownloadTips = holder.binding.simpleGameContainer.downloadTipsLottie
                        multiVersionDownloadTv = holder.binding.simpleGameContainer.multiVersionDownloadTv
                    },
                )
            }

            holder.itemView.setOnClickListener {
                eventHelper.navigateToGameDetailPage(position, item)
            }
        }
    }

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

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

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

    private fun notifyChildItem(packageName: String) {
        dataList.forEachIndexed { index, item ->
            val hasApk = item.getApk().any {
                it.packageName == packageName
            }
            if (hasApk) {
                notifyItemChanged(index, PAYLOAD_REFRESH_GAME_CHANGED)
            }
        }
    }

    class CustomChildIconMatrixViewHolder(
        val binding: RecyclerChildIconMatrixCustomBinding
    ) : ViewHolder(binding.root), IExposureProvider {
        var boundedGameEntity: GameEntity? = null

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