package com.gh.gamecenter.home.gamecollection.refresh

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.game.horizontal.GameHorizontalSimpleItemViewHolder
import com.gh.gamecenter.game.vertical.GameItemUi
import com.gh.gamecenter.game.vertical.GameVerticalAdapter
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.download.DownloadEntity

class HomeGameCollectionRefreshAdapter(
    context: Context,
    private var mIsHorizontal: Boolean,
    private var mSpanCount: Int,
    private var mGameList: List<GameEntity>,
    private val mEntrance: String,
    private val mBlockId: String = "",
    private val mBlockName: String = "",
    private val collectionId: String = "",
    private val collectionName: String = ""
) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {

    private var mCountAndKey: Pair<Int, String>? = null
    private val mMaxWidth = mContext.resources.displayMetrics.widthPixels
    private var mDarkMode = DarkModeUtils.isDarkModeOn(context)

    init {
        var dataIds = ""
        mGameList.forEach {
            dataIds += it.id
        }
        if (dataIds.isNotEmpty()) mCountAndKey = Pair(mGameList.size, dataIds)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
        if (mIsHorizontal) {
            GameHorizontalSimpleItemViewHolder(parent.toBinding())
        } else {
            GameVerticalAdapter.SimpleGameItemViewHolder(GameItemUi(parent.context))
        }

    override fun getItemCount(): Int = mGameList.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is GameVerticalAdapter.SimpleGameItemViewHolder) {
            val gameEntity = mGameList[position]
            holder.bindSimpleGameItem(
                this@HomeGameCollectionRefreshAdapter,
                gameEntity,
                null,
                position,
                mSpanCount,
                mMaxWidth,
                mEntrance,
                "游戏单合集"
            )
            holder.itemView.setOnClickListener {
                NewFlatLogUtils.logGameListCollectionClick(
                    mEntrance,
                    mBlockName,
                    mBlockId,
                    collectionName,
                    collectionId,
                    "游戏"
                )
                SensorsBridge.trackEvent("GameListCollectionClick", json {
                    "location" to if (mEntrance.contains("首页")) "首页" else if (mEntrance.contains("版块")) "版块" else ""
                    "block_name" to mBlockName
                    "block_id" to mBlockId
                    "game_list_collection_name" to collectionName
                    "game_list_collection_id" to collectionId
                    "text" to "游戏"
                    "game_name" to gameEntity.name
                    "game_id" to gameEntity.id
                })
                GameDetailActivity.startGameDetailActivity(
                    mContext,
                    gameEntity.id,
                    mEntrance,
                    traceEvent = gameEntity.exposureEvent
                )
            }
        }

        if (holder is GameHorizontalSimpleItemViewHolder) {
            val gameEntity = mGameList[position]
            holder.binding.run {
                val padR = if (position == itemCount - 1) 16F.dip2px() else 0
                root.setPadding(16F.dip2px(), 0, padR, 0)
                gameName.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                gameIcon.displayGameIcon(gameEntity)
                GameHorizontalSimpleItemViewHolder.setHorizontalNameAndGravity(gameName, gameEntity.name)
                root.setOnClickListener {
                    NewFlatLogUtils.logGameListCollectionClick(
                        mEntrance,
                        mBlockName,
                        mBlockId,
                        collectionName,
                        collectionId,
                        "游戏"
                    )
                    SensorsBridge.trackEvent("GameListCollectionClick", json {
                        "location" to if (mEntrance.contains("首页")) "首页" else if (mEntrance.contains("版块")) "版块" else ""
                        "block_name" to mBlockName
                        "block_id" to mBlockId
                        "game_list_collection_name" to collectionName
                        "game_list_collection_id" to collectionId
                        "text" to "游戏"
                        "game_name" to gameEntity.name
                        "game_id" to gameEntity.id
                    })
                    GameDetailActivity.startGameDetailActivity(
                        mContext,
                        gameEntity.id,
                        mEntrance,
                        gameEntity.exposureEvent
                    )
                }
            }
        }
    }

    fun checkResetData(updateGameList: List<GameEntity>, spanCount: Int) {
        var dataIds = ""
        mGameList = updateGameList
        mSpanCount = spanCount
        mGameList.forEach {
            dataIds += it.id
        }

        if ((mCountAndKey?.first == updateGameList.size && mCountAndKey?.second != dataIds)
            || mDarkMode != DarkModeUtils.isDarkModeOn(mContext)
        ) {
            // 数量不变,内容发生改变
            notifyItemRangeChanged(0, itemCount)
            mDarkMode = DarkModeUtils.isDarkModeOn(mContext)
        } else if (mCountAndKey?.first != updateGameList.size) {
            // 数量发生改变
            notifyDataSetChanged()
        }

        // 重新刷新数据标识
        mCountAndKey = Pair(updateGameList.size, dataIds)
    }

    fun notifyItemByDownload(downloadEntity: DownloadEntity?) {
        if (downloadEntity == null) {
            notifyDataSetChanged()
        } else {
            for (position in mGameList.indices) {
                val entity = mGameList[position]
                if (downloadEntity.gameId == entity.id) {
                    notifyItemChanged(position)
                    return
                }
            }
        }
    }

    fun notifyChildItem(packageName: String) {
        for (position in mGameList.indices) {
            val entity = mGameList[position]
            for (apk in entity.getApk()) {
                if (apk.packageName == packageName) {
                    notifyItemChanged(position)
                }
            }
        }
    }

}