package com.gh.gamecenter.minigame

import androidx.viewpager.widget.PagerAdapter
import com.gh.common.constant.Config
import com.gh.common.filter.RegionSettingHelper
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.databinding.FragmentSearchDefaultBinding
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.search.SearchDefaultFragment

/**
 * 微信小游戏-搜索主页
 */
class MiniGameSearchDefaultFragment : SearchDefaultFragment() {

    override fun initView() {
        mBinding = FragmentSearchDefaultBinding.bind(mCachedView)
        mRankList = Config.getNewApiSettingsEntity()?.search?.wechatGameSearchList?.apply {
            forEachIndexed { outIndex, rankList ->
                rankList.isShowIcon = !rankList.content.any { it.icon.isBlank() }
                var i = 0
                while (i < rankList.content.size) {
                    if (RegionSettingHelper.shouldThisGameBeFiltered(rankList.content[i].linkGame?.id)) {
                        rankList.content.removeAt(i)
                        i--
                    }
                    i++
                }
                rankList.content.forEachIndexed { index, rank ->
                    val source = listOf(ExposureSource("小游戏搜索 -> 搜索榜单", "${rankList.title}-${rank.name}"))
                    if (rank.link.type == "game") {
                        rank.exposureEvent = ExposureEvent.createEvent(
                            rank.linkGame?.toGameEntity()?.apply {
                                outerSequence = outIndex
                                sequence = index
                            },
                            source
                        )
                    } else {
                        rank.exposureEvent = ExposureEvent.createEvent(null, source)
                    }
                }
            }
        }
        defaultViewModel?.isExistRankList = mRankList?.isNotEmpty() == true

        updateHistorySearchView(null)
        defaultViewModel?.historySearchLiveData?.observe(this) {
            updateHistorySearchView(it)
        }

        initHeadView()
        initRankViewPager()
    }

    override fun provideAdapter(pageRatio: Float): PagerAdapter =
        MiniGameSearchDefaultRankListAdapter(requireContext(), mRankList!!, pageRatio)
}