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.RecyclerIconMatrixCustomBinding
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.IGameChangedNotifier
import com.gh.gamecenter.home.custom.adapter.CustomIconMatrixAdapter
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomSplitSubjectItem

/**
 * 游戏专题-图标矩阵
 */
class CustomIconMatrixViewHolder(
    viewModel: CustomPageViewModel,
    val binding: RecyclerIconMatrixCustomBinding
) : BaseCustomViewHolder(viewModel, binding.root) {

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

    private val adapter by lazy {
        CustomIconMatrixAdapter(itemView.context, childEventHelper)
    }

    override val gameChangedNotifier: IGameChangedNotifier
        get() = adapter

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        if (item is CustomSplitSubjectItem) {
            setSplitSubjectTitle(binding.layoutTitle, item, childEventHelper)

            runOnIoThread(isLightWeightTask = true) {
                (item.startChildPosition..item.endChildPosition).forEach {
                    val game = item.data.data?.getOrNull(it) ?: return@forEach
                    fillExposureAndReportAd(game, it, item)
                }
            }

            if (binding.recyclerView.adapter == null) {
                binding.recyclerView.layoutManager =
                    object : GridLayoutManager(itemView.context, 4, RecyclerView.VERTICAL, false) {
                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                binding.recyclerView.adapter = adapter
            }

            adapter.setData(item, item.exposureEventList)
        }
    }

}