package com.gh.gamecenter.personalhome.home.game

import android.content.Context
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.common.util.*
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.core.utils.NumberUtils
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.feature.databinding.GameItemBinding
import com.gh.gamecenter.feature.utils.PlatformUtils
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.gh.gamecenter.mygame.PlayedGameViewModel
import com.lightgame.download.DownloadEntity

class UserPlayedGameAdapter(
    context: Context,
    private val mViewModel: PlayedGameViewModel
) : ListAdapter<GameEntity>(context) {

    private val mEntrance = "个人主页-游戏-玩过"

    val positionAndPackageMap = HashMap<String, Int>()

    override fun setListData(updateData: MutableList<GameEntity>?) {
        // 记录游戏位置
        if (updateData != null) {
            for (i in 0 until updateData.size) {
                val gameEntity = updateData[i]

                // 一些数据置换
                val apk = gameEntity.getApk()
                if (apk.size > 0 && !apk[0].ghVersion.isNullOrEmpty()) {
                    gameEntity.brief = PlatformUtils.getInstance(mContext).getPlatformName(apk[0].getPlatform())
                }

                var packages = gameEntity.id
                for (apkEntity in gameEntity.getApk()) {
                    packages += apkEntity.packageName
                }
                positionAndPackageMap[packages + i] = i
            }
        }
        super.setListData(updateData)
    }

    override fun getItemCount(): Int {
        return if (mEntityList == null || mEntityList.isEmpty()) return 0 else mEntityList.size + 1
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == itemCount - 1) {
            ItemViewType.ITEM_FOOTER
        } else {
            ItemViewType.GAME_NORMAL
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.GAME_NORMAL -> GameItemViewHolder(GameItemBinding.inflate(mLayoutInflater, parent, false))

            else -> FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is GameItemViewHolder -> {
                holder.binding.run {
                    root.setPadding(16F.dip2px(), 8F.dip2px(), 16F.dip2px(), 8F.dip2px())

                    val gameEntity = mEntityList[position]
                    holder.bindGameItem(gameEntity)
                    holder.initServerType(gameEntity)

                    gameDes.run {
                        setTextSize(TypedValue.COMPLEX_UNIT_SP, 11F)
                        setTextColor(R.color.text_subtitle.toColor(mContext))
                    }

                    if (gameEntity.playedTime == 0L) {
                        gameDes.post {
                            gameDes.layoutParams = (gameDes.layoutParams as ConstraintLayout.LayoutParams).apply {
                                topMargin = 8F.dip2px()
                            }
                            gameDesSpace.layoutParams = gameDesSpace.layoutParams.apply {
                                height = gameDes.height + 8F.dip2px()
                            }
                        }
                        labelList.visibility = View.GONE
                    } else {
                        gameDes.layoutParams = (gameDes.layoutParams as ConstraintLayout.LayoutParams).apply {
                            topMargin = 5F.dip2px()
                        }
                        gameDesSpace.layoutParams = gameDesSpace.layoutParams.apply {
                            height = 28F.dip2px()
                        }
                        labelList.visibility = View.VISIBLE
                        labelList.removeAllViews()
                        val runTimeView = TextView(mContext)
                        runTimeView.isSingleLine = true
                        runTimeView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f)
                        runTimeView.setTextColor(R.color.text_subtitle.toColor(mContext))
                        runTimeView.text = "游戏时长 ${NumberUtils.transSimpleUsageTime(gameEntity.playedTime)}"
                        labelList.addView(runTimeView)
                    }

                    DownloadItemUtils.setOnClickListener(
                        mContext,
                        downloadBtn,
                        gameEntity,
                        position,
                        this@UserPlayedGameAdapter,
                        "(${mEntrance})",
                        StringUtils.buildString(mEntrance, ":", gameEntity.name)
                    )
                    DownloadItemUtils.updateItem(mContext, gameEntity, GameViewHolder(holder.binding), true, true)

                    holder.itemView.setOnClickListener {
                        GameDetailActivity.startGameDetailActivity(mContext, gameEntity.id, "(${mEntrance})")
                    }
                }
            }

            is FooterViewHolder -> holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
        }
    }

    fun notifyItemByDownload(download: DownloadEntity) {
        for (key in positionAndPackageMap.keys) {
            // sentry上报download.packageName可能为空
            if (download.packageName != null
                && download.gameId != null
                && key.contains(download.packageName)
                && key.contains(download.gameId)
            ) {
                val position = positionAndPackageMap[key]
                if (position != null && mEntityList != null && position < mEntityList.size) {
                    mEntityList[position].getEntryMap()[download.platform] = download
                    notifyItemChanged(position)
                }
            }
        }
    }

    fun notifyItemAndRemoveDownload(status: EBDownloadStatus) {
        for (key in positionAndPackageMap.keys) {
            if (key.contains(status.packageName) && key.contains(status.gameId)) {
                val position = positionAndPackageMap[key]
                if (position != null && mEntityList != null && position < mEntityList.size) {
                    mEntityList[position].getEntryMap().remove(status.platform)
                    notifyItemChanged(position)
                }
            }
        }
    }

}