package com.gh.gamecenter.download

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureManager
import com.gh.common.util.DownloadItemUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.entity.AdConfig
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.gh.gamecenter.feature.minigame.MiniGameItemHelper
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.download.DownloadEntity

class AdGameBannerAdapter(
    context: Context,
    private val mAdConfig: AdConfig,
    private val mSnapHelper: PagerSnapHelper,
    private val mLayoutManager: LinearLayoutManager,
    private val mEntrance: String
) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {

    private var mGameEntityList = emptyList<GameEntity>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = GameItemViewHolder(parent.toBinding())
    fun submitList(updateList: List<GameEntity>) {
        mGameEntityList = ArrayList(updateList)
        AppExecutor.uiExecutor.execute {
            notifyDataSetChanged()
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is GameItemViewHolder) {
            mGameEntityList.safelyGetInRelease(getActualPosition(position))?.let {
                val exposureEvent = ExposureEvent.createEvent(
                    gameEntity = it,
                    source = listOf(ExposureSource(mEntrance, ""), ExposureSource("banner广告", ""))
                )
                ExposureManager.log(exposureEvent)

                holder.bindGameItem(it)
                holder.initServerType(it)

                DownloadItemUtils.setOnClickListener(
                    mContext,
                    holder.binding.downloadBtn,
                    it,
                    position,
                    this,
                    mEntrance,
                    location = "banner广告",
                    traceEvent = exposureEvent,
                    clickCallback = {
                        NewFlatLogUtils.logClickGameAd(
                            mAdConfig.id,
                            mAdConfig.name,
                            "下载管理",
                            mAdConfig.typeChinese,
                            mAdConfig.ownerAd?.id ?: "",
                            mAdConfig.ownerAd?.sourceName ?: "",
                            it.id,
                            it.name ?: ""
                        )
                    }
                )
                DownloadItemUtils.updateItem(
                    mContext,
                    it,
                    GameViewHolder(holder.binding)
                )

                holder.binding.root.setOnClickListener { _ ->
                    NewFlatLogUtils.logClickGameAd(
                        mAdConfig.id,
                        mAdConfig.name,
                        "下载管理",
                        mAdConfig.typeChinese,
                        mAdConfig.ownerAd?.id ?: "",
                        mAdConfig.ownerAd?.sourceName ?: "",
                        it.id,
                        it.name ?: ""
                    )
                    if (it.isMiniGame()) {
                        MiniGameItemHelper.launchMiniGame(it)
                    } else {
                        GameDetailActivity.startGameDetailActivity(
                            mContext,
                            it,
                            BaseActivity.mergeEntranceAndPath(mEntrance, "banner广告"),
                            exposureEvent
                        )
                    }
                }
            }
        }
    }

    fun getActualPosition(position: Int): Int {
        var actualPosition = position
        val actualSize = getActualSize()
        if (actualSize in 1..position) {
            actualPosition = position % actualSize
        }
        return actualPosition
    }

    fun getActualSize() = mGameEntityList.size

    fun getActualFirstPositionInCenter(): Int {
        var index = itemCount / 2
        while (getActualPosition(index) != 0) {
            index++
        }
        return index
    }

    override fun getItemCount() = if (getActualSize() <= 1) getActualSize() else Int.MAX_VALUE

    fun notifyItemByDownload(downloadEntity: DownloadEntity) {
        val snapView = mSnapHelper.findSnapView(mLayoutManager)
        if (snapView != null) {
            val position = mLayoutManager.getPosition(snapView)
            if (position != -1) {
                val actualPosition = getActualPosition(position)
                if (actualPosition < mGameEntityList.size) {
                    val game = mGameEntityList[actualPosition]
                    if (game != null && game.id == downloadEntity.gameId) {
                        notifyItemChanged(position)
                    }
                }
            }
        }
    }
}