package com.gh.gamecenter.catalog

import android.content.Context
import android.util.SparseArray
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.IExposable
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
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.utils.dip2px
import com.gh.gamecenter.common.utils.toBinding
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.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureSource
import com.gh.gamecenter.feature.exposure.ExposureType
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.lightgame.download.DownloadEntity

class NewCatalogListAdapter(
    context: Context,
    private val mBaseExposureSource: ExposureSource,
    private val mViewModel: NewCatalogListViewModel,
    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): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.GAME_NORMAL -> {
                GameItemViewHolder(parent.toBinding())
            }
            else -> {
                FooterViewHolder(mLayoutInflater.inflate(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: RecyclerView.ViewHolder, position: Int) {
        if (holder is GameItemViewHolder) {
            val padTop = if (position == 0) 16F.dip2px() else 8F.dip2px()
            holder.itemView.setPadding(16F.dip2px(), padTop, 16F.dip2px(), 8F.dip2px())

            val gameEntity = mEntityList[position]

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

            val sortType = mViewModel.sortType.value
            val sortSize = mViewModel.sortSize.text
            val toolbarTitle = mViewModel.title
            val selectedCatalogName = mViewModel.selectedCatalog.name

            val exposureSources = ArrayList<ExposureSource>()
            exposureSources.add(mBaseExposureSource)
            exposureSources.add(ExposureSource(toolbarTitle))
            exposureSources.add(ExposureSource("二级分类详情", "$selectedCatalogName+$sortType+$sortSize"))

            val event = ExposureEvent.createEvent(gameEntity, exposureSources, null, ExposureType.EXPOSURE)
            mExposureEventSparseArray.put(position, event)

            holder.itemView.setOnClickListener {
                GameDetailActivity.startGameDetailActivity(
                    mContext,
                    gameEntity,
                    StringUtils.buildString(
                        mEntrance,
                        "+(",
                        toolbarTitle,
                        ":列表[",
                        selectedCatalogName,
                        "=",
                        sortType,
                        "=",
                        (position + 1).toString(),
                        "])"
                    ),
                    traceEvent = event
                )
            }
            DownloadItemUtils.setOnClickListener(
                mContext,
                holder.binding.downloadBtn,
                gameEntity,
                position,
                this,
                StringUtils.buildString(
                    StringUtils.buildString(
                        mEntrance,
                        "+(",
                        toolbarTitle,
                        ":列表[",
                        selectedCatalogName,
                        "=",
                        sortType,
                        "=",
                        (position + 1).toString(),
                        "])"
                    )
                ),
                StringUtils.buildString(selectedCatalogName, ":", gameEntity.name),
                event
            )

            DownloadItemUtils.updateItem(mContext, gameEntity, GameViewHolder(holder.binding), true, "star&brief")
        } else if (holder is FooterViewHolder) {
            holder.initItemPadding()
            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)
                }
            }
        }
    }

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

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

}