package com.adealink.weparty.playmate.list.adapter

import androidx.fragment.app.Fragment
import com.adealink.weparty.commonui.recycleview.adapter.BaseTabFragmentStateAdapter
import com.adealink.weparty.module.playmate.data.PlaymateCategoryData

data class PageData(
    val data: PlaymateCategoryData,
    val pageId: Long
)

abstract class BaseHomePageAdapter(fragment: Fragment) : BaseTabFragmentStateAdapter(fragment) {

    val pages = mutableListOf<PageData>()

    fun setCategory(category: List<PlaymateCategoryData>) {
        if (!checkCategoryChanged(category)) {
            return
        }
        pages.clear()
        pages.addAll(category.map {
            PageData(it, it.code.hashCode().toLong())
        })
        notifyDataSetChanged()
    }

    private fun checkCategoryChanged(category: List<PlaymateCategoryData>): Boolean {
        if (category.isEmpty()) {
            return false
        }
        val nextCodeList = category.map { it.code }
        val currentCodeList = pages.map { it.data.code }
        if (nextCodeList.size != currentCodeList.size) {
            return true
        }
        for (i in 0 until nextCodeList.size) {
            val nextCode = nextCodeList[i]
            val currentCode = currentCodeList[i]
            if (nextCode != currentCode) {
                return true
            }
        }
        return false
    }

    override fun getItemId(position: Int): Long {
        val hash = pages.getOrNull(position)?.pageId ?: 0L
        return hash
    }

    override fun containsItem(itemId: Long): Boolean {
        return super.containsItem(itemId)
    }

    override fun getTabName(pos: Int): String {
        return pages.getOrNull(pos)?.data?.name ?: ""
    }

    override fun getItemCount(): Int {
        return pages.size
    }

    abstract override fun createFragment(position: Int): Fragment

}