package com.gh.gamecenter.home.slide

import android.content.Context
import android.os.Handler
import android.os.Message
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.databind.BindingAdapters
import com.gh.common.exposure.ExposureEvent
import com.gh.common.exposure.ExposureSource
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.DataLogUtils
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.PageSwitchDataHelper
import com.gh.gamecenter.databinding.HomeSlideListItemBinding
import com.gh.gamecenter.entity.HomeSlide
import com.gh.gamecenter.home.HomeItemData
import com.gh.gamecenter.setting.SettingBridge
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.download.DownloadEntity
import java.lang.ref.WeakReference

class HomeSlideListAdapter(
    context: Context,
    var itemData: HomeItemData,
    val layoutManager: LinearLayoutManager,
    val snapHelper: PagerSnapHelper,
    val recyclerView: RecyclerView,
    val basicExposureSource: List<ExposureSource>
) : BaseRecyclerAdapter<HomeSlideListItemViewHolder>(context) {

    private var mSlideList: List<HomeSlide> = itemData.slides ?: arrayListOf()
    private val mLooperHandle = LooperHandle(this)
    private val mSlideLooperKey = 456
    private val mSlideLooperInterval: Long = 5000

    init {
        startScroll()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeSlideListItemViewHolder {
        val view = mLayoutInflater.inflate(R.layout.home_slide_list_item, parent, false)
        return HomeSlideListItemViewHolder(HomeSlideListItemBinding.bind(view))
    }

    override fun getItemCount(): Int {
        return if (itemData.slides?.size == 1) 1 else Int.MAX_VALUE
    }

    override fun onBindViewHolder(holder: HomeSlideListItemViewHolder, position: Int) {
        val actualPosition = getActualPosition(position)
        if (actualPosition > mSlideList.size) {
            holder.itemView.post {
                notifyItemChanged(position)
            }
            return
        }

        val homeSlide = mSlideList[actualPosition]

        var exposureEvent: ExposureEvent? = null
        if (homeSlide.linkType == "game") {
            runOnIoThread(true) {
                exposureEvent = ExposureEvent.createEventWithSourceConcat(
                    gameEntity = homeSlide.linkGame?.apply { sequence = actualPosition },
                    basicSource = basicExposureSource,
                    source = listOf(ExposureSource("轮播图", ""))
                )
                itemData.exposureEventList?.add(exposureEvent!!)
            }
        } else {
            exposureEvent = ExposureEvent.createEventWithSourceConcat(
                gameEntity = homeSlide.linkGame?.apply { sequence = actualPosition },
                basicSource = basicExposureSource,
                source = listOf(ExposureSource("轮播图", ""))
            )
            exposureEvent?.payload?.controlType = "轮播图"
            exposureEvent?.payload?.controlName = homeSlide.title
            exposureEvent?.payload?.controlLinkName = homeSlide.linkText
            exposureEvent?.payload?.controlLinkType = homeSlide.linkType
            itemData.exposureEventList?.add(exposureEvent!!)
        }

        holder.bindSlideListItem(homeSlide)
        holder.binding.root.setOnClickListener {
            val actualPositionString = (actualPosition + 1).toString()
            if (homeSlide.linkType == "video") {
                MtaHelper.onEvent("首页_新", "轮播_点击", actualPositionString + "_视频详情")
            } else if (homeSlide.linkType == "game") {
                MtaHelper.onEvent("首页_新", "轮播_点击", actualPositionString + "_游戏详情")
            }

            PageSwitchDataHelper.pushCurrentPageData(
                hashMapOf(
                    Pair(PageSwitchDataHelper.PAGE_BUSINESS_TYPE, "首页轮播图")
                )
            )

            DataLogUtils.uploadLunbotuLog(
                mContext,
                homeSlide.linkType,
                homeSlide.linkText,
                homeSlide.title,
                actualPositionString,
                "新首页"
            )
            DirectUtils.directToLinkPage(mContext,
                homeSlide.transformLinkEntity(),
                "",
                "新首页-轮播图[${homeSlide.linkText}<-||->${homeSlide.title}=${homeSlide.linkType}=$actualPositionString]",
                exposureEvent,
                unknownCallback = {
                    mContext.startActivity(SettingBridge.getAboutIntent(mContext, true))
                })
        }

        holder.binding.includeGame.root.setOnClickListener {
            val actualPositionString = (actualPosition + 1).toString()
            val linkGame = homeSlide.linkGame
            DataLogUtils.uploadLunbotuLog(
                mContext,
                homeSlide.linkType,
                homeSlide.linkText,
                homeSlide.title,
                actualPositionString,
                "新首页"
            )
            if (linkGame != null) {
                GameDetailActivity.startGameDetailActivity(
                    mContext,
                    linkGame.id,
                    "(新首页-轮播图[${homeSlide.linkText}<-||->${homeSlide.title}=${homeSlide.linkType}=$actualPositionString])",
                    exposureEvent
                )
            }
        }
        BindingAdapters.setGameTags(holder.binding.includeGame.gameTags, homeSlide.linkGame?.tagStyle, 3)
        holder.binding.unknownBackground.goneIf(DirectUtils.directLinkTypes.contains(homeSlide.linkType))
    }

    fun getActualPosition(position: Int): Int {
        var actualPosition = position
        if (mSlideList.size in 1..position) {
            actualPosition = position % mSlideList.size
        }
        return actualPosition
    }

    fun checkResetData(updateList: List<HomeSlide>) {
        if (updateList != mSlideList) {
            val isSameSize = updateList.size == mSlideList.size
            mSlideList = ArrayList(updateList)
            if (isSameSize) {
                val view = snapHelper.findSnapView(layoutManager) ?: return
                val centerPosition = layoutManager.getPosition(view)
                val startPosition = if (centerPosition > 0) centerPosition - 1 else centerPosition
                notifyItemRangeChanged(startPosition, 3)
            } else {
                notifyDataSetChanged()
            }
        }

        startScroll()
    }

    fun notifyItemByDownload(downloadEntity: DownloadEntity?) {
        if (downloadEntity == null) {
            notifyDataSetChanged()
        } else {
            val snapView = snapHelper.findSnapView(layoutManager)
            if (snapView != null) {
                val position = layoutManager.getPosition(snapView)
                if (position != -1) {
                    for (index in getCheckPositions(getActualPosition(position))) {
                        if (index >= 0 && index < mSlideList.size) {
                            val game = mSlideList[index].linkGame
                            if (game != null && game.id == downloadEntity.gameId) {
                                notifyItemChanged(position)
                            }
                        }
                    }
                }
            }
        }
    }

    fun scrollToNextPage() {
        val snapView = snapHelper.findSnapView(layoutManager)
        if (snapView != null) {
            layoutManager.smoothScrollToPosition(recyclerView, null, layoutManager.getPosition(snapView) + 1)
        }
    }

    private fun getCheckPositions(actualPosition: Int): List<Int> {
        return arrayListOf(actualPosition - 1, actualPosition, actualPosition + 1)
    }

    fun startScroll() {
        mLooperHandle.removeMessages(mSlideLooperKey)
        mLooperHandle.sendEmptyMessageDelayed(mSlideLooperKey, mSlideLooperInterval)
    }

    fun stopScroll() {
        mLooperHandle.removeMessages(mSlideLooperKey)
    }

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

    class LooperHandle(adapter: HomeSlideListAdapter) : Handler() {
        private val mWeakReference: WeakReference<HomeSlideListAdapter> = WeakReference(adapter)

        override fun handleMessage(msg: Message) {
            val adapter = mWeakReference.get()
            if (adapter != null) {
                if (msg.what == adapter.mSlideLooperKey) {
                    adapter.scrollToNextPage()
                    adapter.startScroll()
                }
            }
        }
    }
}