package com.gallery.free.wallpaper

import android.util.Log
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gallery.free.wallpaper.fragment.WpGridFragment

class HoPagerAdapter(
    fragment: Fragment,
    private val categories: List<String> = listOf("Film", "Nature", "Travel")
) : FragmentStateAdapter(fragment) {

    companion object {
        private const val TAG = "HomePagerAdapter"
    }

    private val fragments = mutableMapOf<Int, WpGridFragment>()

    override fun getItemCount(): Int = categories.size

    override fun createFragment(position: Int): Fragment {
        val categoryName = categories[position]
        val fragment = WpGridFragment.newInstance(categoryName)
        fragments[position] = fragment

        Log.d(TAG, "创建Fragment - 位置: $position, 分类: $categoryName")
        return fragment
    }

    fun getTabTitle(position: Int): String {
        return if (position in categories.indices) {
            categories[position]
        } else {
            ""
        }
    }

    fun getFragment(position: Int): WpGridFragment? {
        return fragments[position]
    }

    /**
     * 更新分类列表
     */
    fun updateCategories(newCategories: List<String>) {
        Log.d(TAG, "更新分类列表: $newCategories")
    }

    /**
     * 获取所有 Fragment
     */
    fun getAllFragments(): List<WpGridFragment> {
        return fragments.values.toList()
    }

    /**
     * 清除 Fragment 缓存
     */
    fun clearFragmentCache() {
        fragments.clear()
        Log.d(TAG, "已清除Fragment缓存")
    }
}