package com.gh.gamecenter.servers.gametest2

import android.content.Context
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.IExposable
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.databinding.ItemGameServerTestTimeBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureSource
import com.gh.gamecenter.feature.game.GameItemViewHolder

class GameServerTestV2ListAdapter(
    val context: Context,
    private val mEntrance: String,
    private var mGameServerTestV2ViewModel: GameServerTestV2ViewModel?,
    private var mBasicExposureSource: List<ExposureSource>?,
    private var mOuterSequence: Int,
) : ListAdapter<GameServerTestV2ListViewModel.ItemData>(context), IExposable {

    private val mExposureEventArray: SparseArray<ExposureEvent> = SparseArray()

    override fun areItemsTheSame(
        oldItem: GameServerTestV2ListViewModel.ItemData?,
        newItem: GameServerTestV2ListViewModel.ItemData?
    ): Boolean {
        if (oldItem?.time != null && newItem?.time != null) {
            return oldItem.time == newItem.time
        }
        if (oldItem?.game != null && newItem?.game != null) {
            return oldItem.game?.id == newItem.game?.id
        }
        return false
    }

    override fun getItemViewType(position: Int): Int {
        if (position == mEntityList.size) {
            return VIEW_TYPE_FOOTER
        }
        return when {
            mEntityList[position].time != null -> VIEW_TYPE_TIME
            mEntityList[position].isBigImage -> VIEW_TYPE_BIG_IMAGE_ITEM
            else -> VIEW_TYPE_ITEM
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            VIEW_TYPE_FOOTER -> {
                FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            }
            VIEW_TYPE_TIME -> {
                GameServerTestTimeViewHolder(parent.toBinding())
            }
            VIEW_TYPE_BIG_IMAGE_ITEM -> {
                GameBigImageViewHolder(parent.toBinding())
            }
            else -> {
                GameItemViewHolder(parent.toBinding())
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is GameItemViewHolder -> {
                val itemData = mEntityList[position]
                val gameEntity = itemData.game!!
                val isTheLastOfTheLatestConsecutiveGame = itemData.isTheLastOfTheLatestConsecutiveGame
                holder.itemView.setPadding(
                    16F.dip2px(),
                    8F.dip2px(),
                    16F.dip2px(),
                    if (isTheLastOfTheLatestConsecutiveGame) 16F.dip2px() else 8F.dip2px()
                )
                holder.bindGameItem(gameEntity, forceShowSubtitle = true)
                holder.binding.gameDes.setTextColor(R.color.text_title.toColor(context))
                initGameItemViewHolder(gameEntity, holder, position)
            }
            is GameBigImageViewHolder -> {
                val gameEntity = mEntityList[position].game!!
                val exposureEvent = putExposureEvent(gameEntity, position)

                holder.bindAttachGame(
                    holder,
                    gameEntity,
                    this,
                    "新游开测",
                    exposureEvent
                )
            }
            is GameServerTestTimeViewHolder -> {
                holder.binding.timeTv.text = mEntityList[position].time
            }
            is FooterViewHolder -> {
                initFooterViewHolder(holder)
            }
        }
    }

    private fun putExposureEvent(
        gameEntity: GameEntity,
        position: Int
    ): ExposureEvent {
        val exposureSources = ArrayList<ExposureSource>()
        val tabFilter =
            if (mGameServerTestV2ViewModel?.tabFilter == GameServerTestV2ViewModel.TestFilter.RECOMMEND) {
                "推荐"
            } else {
                "全部"
            }
        val selectedCategoryFilter = mGameServerTestV2ViewModel?.selectedCategoryFilter
        val selectedTimeFilter = mGameServerTestV2ViewModel?.selectedTimeFilterLiveData?.value
        exposureSources.add(
            ExposureSource(
                "新游开测",
                "${tabFilter}-${selectedCategoryFilter}-${selectedTimeFilter}-${gameEntity.testTime}"
            )
        )
        val exposureEvent = ExposureEvent.createEventWithSourceConcat(
            gameEntity = gameEntity.apply {
                outerSequence = mOuterSequence
                sequence = position
            },
            basicSource = mBasicExposureSource ?: listOf(),
            source = exposureSources
        )
        mExposureEventArray.put(position, exposureEvent)
        return exposureEvent
    }

    private fun initGameItemViewHolder(gameEntity: GameEntity, viewHolder: GameItemViewHolder, position: Int) {
        val exposureEvent = putExposureEvent(gameEntity, position)
        DownloadItemUtils.setOnClickListener(
            mContext,
            viewHolder.binding.downloadBtn, gameEntity, position, this,
            StringUtils.buildString(mEntrance, "+(新游开测[", position.toString(), "])"),
            StringUtils.buildString("新游开测:", gameEntity.name),
            exposureEvent
        )
        DownloadItemUtils.updateItem(
            mContext,
            gameEntity,
            GameViewHolder(viewHolder.binding),
            true,
//            "star&brief"
        )
        viewHolder.binding.gameDes.text = gameEntity.brief
        viewHolder.itemView.setOnClickListener {
            GameDetailActivity.startGameDetailActivity(
                mContext, gameEntity,
                StringUtils.buildString(mEntrance, "+(新游开测[", viewHolder.adapterPosition.toString(), "])"),
                traceEvent = exposureEvent
            )
        }
    }

    private fun initFooterViewHolder(viewHolder: FooterViewHolder) {
        viewHolder.run {
            itemView.setBackgroundColor(R.color.background.toColor(mContext))
            loading.visibility = View.GONE
            itemView.isClickable = false
            hint.setText(R.string.load_over_hint)
        }
    }

    override fun getItemCount(): Int = if (mEntityList.isEmpty()) 0 else mEntityList.size + 1

    companion object {
        const val VIEW_TYPE_TIME = 0
        const val VIEW_TYPE_ITEM = 1
        const val VIEW_TYPE_BIG_IMAGE_ITEM = 2
        const val VIEW_TYPE_FOOTER = 3
    }

    class GameServerTestTimeViewHolder(var binding: ItemGameServerTestTimeBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun getEventByPosition(pos: Int): ExposureEvent? {
        return mExposureEventArray.get(pos)
    }

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? {
        return null
    }
}