package com.gh.gamecenter.tag

import android.content.Context
import android.util.SparseArray
import android.view.ViewGroup
import com.gh.common.exposure.IExposable
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.feature.databinding.GameItemBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.lightgame.download.DownloadEntity

class TagsListAdapter(
    context: Context,
    private val mViewModel: TagsListViewModel,
    private val mEntrance: String?
) : ListAdapter<GameEntity>(context), IExposable {

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

    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]
                var packages = gameEntity.id
                for (apkEntity in gameEntity.getApk()) {
                    packages += apkEntity.packageName
                }
                positionAndPackageMap[packages + i] = i
            }
        }
        super.setListData(updateData)
    }

    fun clearPositionAndPackageMap() {
        positionAndPackageMap.clear()
    }

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

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

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): androidx.recyclerview.widget.RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.GAME_NORMAL -> {
                GameItemViewHolder(GameItemBinding.bind(mLayoutInflater.inflate(com.gh.gamecenter.feature.R.layout.game_item, parent, false)))
            }
            else -> {
                FooterViewHolder(mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false))
            }
        }
    }

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

    override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
        if (holder is GameItemViewHolder) {
            val gameEntity = mEntityList[position]

            holder.bindGameItem(gameEntity)
            holder.initServerType(gameEntity)

            val padTop = if (position == 0) 16F.dip2px() else 8F.dip2px()
            holder.itemView.setPadding(16F.dip2px(), padTop, 16F.dip2px(), 8F.dip2px())

            val exposureSource =
                ExposureSource("标签详情", "${mViewModel.selectedTag.name} + ${mViewModel.getSortTypeInChinese()}")
            val exposureSourceList = arrayListOf<ExposureSource>()
            val exposureEvent = ExposureEvent.createEvent(gameEntity, exposureSourceList)
            exposureSourceList.addAll(mViewModel.basicExposureSourceList)
            exposureSourceList.add(exposureSource)
            gameEntity.exposureEvent = exposureEvent
            mExposureEventSparseArray.append(position, exposureEvent)

            holder.itemView.setOnClickListener {
                GameDetailActivity.startGameDetailActivity(
                    mContext,
                    gameEntity,
                    mEntrance ?: "",
                    traceEvent = exposureEvent
                )
            }
            DownloadItemUtils.setOnClickListener(
                mContext,
                holder.binding.downloadBtn,
                gameEntity,
                position,
                this,
                StringUtils.buildString(
                    mEntrance,
                    "+(标签详情[",
                    mViewModel.selectedTag.name,
                    "]:列表[",
                    (position + 1).toString(),
                    "])"
                ),
                location = StringUtils.buildString(mViewModel.selectedTag.name, ":", gameEntity.name),
                traceEvent = exposureEvent
            )
            DownloadItemUtils.updateItem(mContext, gameEntity, GameViewHolder(holder.binding))
        } else if (holder is FooterViewHolder) {
            holder.initItemPadding()
            holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
        }
    }

    fun notifyItemByDownload(download: DownloadEntity) {
        for (key in positionAndPackageMap.keys) {
            if (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)
                }
            }
        }
    }

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

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