package com.gh.gamecenter.search.adapter

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gh.gamecenter.SearchActivity
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.feature.entity.SettingsEntity
import com.gh.gamecenter.feedback.view.qa.HelpContentFragment
import com.gh.gamecenter.forum.search.ForumContentSearchListFragment
import com.gh.gamecenter.forum.search.UserSearchListFragment
import com.gh.gamecenter.minigame.MiniGameSearchResultFragment
import com.gh.gamecenter.qa.dialog.ChooseForumContainerFragment
import com.gh.gamecenter.search.SearchGameResultFragment
import com.gh.gamecenter.search.fragment.SearchGameListFragment

class SearchTabAdapter(
    private val location: String,
    private val searchType: String?,
    private val tabs: List<SettingsEntity.Search.Navigation>,
    private val fragment: Fragment
) : FragmentStatePagerAdapter(fragment.childFragmentManager,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

    override fun getPageTitle(position: Int): CharSequence {
        return tabs[position].title
    }

    override fun getCount(): Int = tabs.size

    override fun getItem(position: Int): Fragment {
        val navigation = tabs[position]
        val bundle = Bundle().apply {
            putBoolean(EntranceConsts.KEY_IS_AUTO_LOAD, false)
            putString(EntranceConsts.KEY_LOCATION, location)
        }
        val fragment = when (navigation.type) {
            SEARCH_TYPE_GAME -> SearchGameResultFragment()

            SEARCH_TYPE_BBS -> ChooseForumContainerFragment.getInstance(ChooseForumContainerFragment.ChooseForumType.SEARCH)

            SEARCH_TYPE_BBS_CONTENT -> ForumContentSearchListFragment()

            SEARCH_TYPE_USER -> UserSearchListFragment()

            SEARCH_TYPE_MINI_GAME -> MiniGameSearchResultFragment()

            SEARCH_TYPE_QA -> HelpContentFragment().apply {
                arguments = Bundle().apply {
                    putString(EntranceConsts.KEY_SEARCH_TYPE, SearchActivity.toTrackSearchType(searchType ?: ""))
                }
            }

            SEARCH_TYPE_GAME_LIST -> SearchGameListFragment()

            else -> SearchGameResultFragment()
        }.also {
            if (it.arguments != null) {
                it.arguments?.putAll(bundle)
            } else {
                it.arguments = bundle
            }

        }
        return fragment
    }

    companion object {
        private const val SEARCH_TYPE_GAME = "game"
        private const val SEARCH_TYPE_BBS = "bbs"
        private const val SEARCH_TYPE_BBS_CONTENT = "bbs_content"
        private const val SEARCH_TYPE_USER = "user"
        private const val SEARCH_TYPE_QA = "qa"
        private const val SEARCH_TYPE_MINI_GAME = "mini_game"
        private const val SEARCH_TYPE_GAME_LIST = "game_list"
    }
}