package com.gh.gamecenter.feature.game

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.feature.entity.InstallGameEntity
import com.lightgame.adapter.BaseRecyclerAdapter

class SuggestSelectGameAdapter(
    context: Context,
    private val mPlatformRequestsId: String = "",
    private val mClickAction: (InstallGameEntity) -> Unit
) :
    BaseRecyclerAdapter<SelectGameViewHolder>(context) {
    private var mInstallGameList: List<InstallGameEntity> = listOf()

    fun submitList(data: List<InstallGameEntity>) {
        mInstallGameList = ArrayList(data)
        notifyDataSetChanged()
    }

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

    override fun getItemCount(): Int = mInstallGameList.size

    override fun onBindViewHolder(holder: SelectGameViewHolder, position: Int) {
        val row = if (itemCount % 4 == 0) itemCount / 4 else itemCount / 4 + 1
        val isFirstRow = position / 4 == 0
        val isLastRow = position / 4 == row - 1
        holder.binding.root.layoutParams = (holder.binding.root.layoutParams as MarginLayoutParams).apply {
            setMargins(0, if (isFirstRow) 8F.dip2px() else 0, 0, if (isLastRow) 8F.dip2px() else 0)
        }
        mInstallGameList.safelyGetInRelease(position)?.let { installGameEntity ->
            if (mPlatformRequestsId.isNotEmpty()) {
                installGameEntity.platformRequestsId = mPlatformRequestsId
            }
            installGameEntity.gameBm?.let { holder.binding.gameIcon.getIconIv().setImageBitmap(it) }
            installGameEntity.gameIcon?.let { holder.binding.gameIcon.displayGameIcon(it, null) }
            holder.binding.gameIcon.getIconDecoratorIv().visibility = View.GONE
            holder.binding.gameName.text = installGameEntity.gameName
            holder.binding.gameName.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))

            holder.binding.root.setOnClickListener {
                mClickAction(installGameEntity)
            }
        }

    }
}