package com.gh.gamecenter.minigame

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.baselist.DiffUtilAdapter
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.databinding.ItemHomeVgameBinding
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.minigame.MiniGameItemHelper

/**
 * 微信小游戏-最近在玩列表
 */
class MiniGameRecentlyPlayListAdapter(
    context: Context,
    private val onItemClick: ((GameEntity, Int) -> Unit)? = null
) : DiffUtilAdapter<GameEntity>(context) {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): MiniGameRecentlyPlayItemViewHolder {
        return MiniGameRecentlyPlayItemViewHolder(parent.toBinding())
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        (holder as MiniGameRecentlyPlayItemViewHolder).bindView(mDataList[position], position, onItemClick)
    }

    override fun getItemCount(): Int {
        return mDataList.size
    }

    override fun areItemsTheSame(oldItem: GameEntity?, newItem: GameEntity?): Boolean {
        return oldItem == newItem
    }

    override fun areContentsTheSame(oldItem: GameEntity?, newItem: GameEntity?): Boolean {
        return oldItem == newItem
    }

    class MiniGameRecentlyPlayItemViewHolder(private var mBinding: ItemHomeVgameBinding) :
        RecyclerView.ViewHolder(mBinding.root), IExposureProvider {

        private var exposureEvent: ExposureEvent? = null

        fun bindView(entity: GameEntity, position: Int, onItemClick: ((GameEntity, Int) -> Unit)? = null) {
            exposureEvent = entity.exposureEvent

            mBinding.gameIconIv.displayGameIcon(entity)

            mBinding.maskView.visibility = View.GONE
            mBinding.controlTv.visibility = View.GONE
            mBinding.progressBar.visibility = View.GONE
            mBinding.dotView.visibility = View.GONE
            mBinding.updateHintIv.visibility = View.GONE
            mBinding.controlTv.visibility = View.GONE
            mBinding.progressBar.visibility = View.GONE

            mBinding.root.setOnClickListener {
                if (onItemClick != null) {
                    onItemClick.invoke(entity, position)
                } else {
                    MiniGameItemHelper.launchMiniGame(entity)
                }
            }
        }

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