package com.gh.gamecenter.home.custom.viewholder

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.GameVerticalSlideItemCustomBinding
import com.gh.gamecenter.game.vertical.SpanCountPagerSnapHelper
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.IGameChangedNotifier
import com.gh.gamecenter.home.custom.adapter.CustomGameVerticalAdapter
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomSubjectItem

/**
 * 游戏专题-滑动列表
 */
class CustomGameVerticalSlideViewHolder(
    viewModel: CustomPageViewModel,
    val binding: GameVerticalSlideItemCustomBinding,
) :
    BaseCustomViewHolder(viewModel, binding.root) {

    override val childEventHelper by lazy(LazyThreadSafetyMode.NONE) {
        SubjectEventHelper(viewModel)
    }

    private val adapter by lazy {
        CustomGameVerticalAdapter(
            itemView.context, pageConfigure.transparentBackground,
            childEventHelper
        )
    }

    override val gameChangedNotifier: IGameChangedNotifier?
        get() = adapter

    init {
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.itemAnimator = null
    }

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        if (item is CustomSubjectItem) {
            setSubjectTitle(binding.layoutTitle, item, childEventHelper, TITLE_TYPE_SMALL)
            val subjectEntity = item.data
            val games = subjectEntity.data ?: return

            binding.recyclerView.clearOnScrollListeners()
            binding.recyclerView.onFlingListener = null
            val spanCount = subjectEntity.list

            val snapHelper = SpanCountPagerSnapHelper(spanCount, true)
            if (binding.recyclerView.layoutManager == null) {
                val layoutManager = GridLayoutManager(itemView.context, spanCount, RecyclerView.HORIZONTAL, false)
                binding.recyclerView.layoutManager = layoutManager
                binding.recyclerView.adapter = adapter
            } else {
                val gridLayoutManager = binding.recyclerView.layoutManager as? GridLayoutManager
                if (gridLayoutManager?.spanCount != spanCount) {
                    gridLayoutManager?.spanCount = spanCount
                }
            }

            runOnIoThread(isLightWeightTask = true) {
                games.forEachIndexed { index, gameEntity ->
                    fillExposureAndReportAd(gameEntity, index, item)
                }
            }

            adapter.setData(item.data)

            snapHelper.attachToRecyclerView(binding.recyclerView)
        }
    }
}
