package com.gh.gamecenter.forum.home.follow

import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.utils.DarkModeUtils

class ResetDataChangeHelper<T>(
    private val context: Context,
    private val adapter: RecyclerView.Adapter<*>
) {

    private var darkMode = DarkModeUtils.isDarkModeOn(context)

    private val _dataList = arrayListOf<T>()
    val dataList: List<T> = _dataList

    val dataCount: Int
        get() = dataList.size

    fun getItem(position: Int) = dataList[position]

    private var _countAndKey: Pair<Int, String>? = null

    fun submitList(data: List<T>?, getKey: (T) -> String) {
        _dataList.clear()
        data?.let(_dataList::addAll)

        if (data.isNullOrEmpty()) {
            _countAndKey = null
            adapter.notifyDataSetChanged()
            return
        }
        val countAndKey = _countAndKey ?: Pair(0, "")
        val (oldSize, oldKeys) = countAndKey

        val newSize = data.size
        var newKeys = ""
        data.forEach {
            newKeys += getKey(it)
        }
        if (oldSize == newSize) {
            if (oldKeys != newKeys || darkMode != DarkModeUtils.isDarkModeOn(context)) { // 数量不变，内容发生变化 || 切换浅色模式
                adapter.notifyItemRangeChanged(0, adapter.itemCount, "")
            }
        } else {// 数量发生变化
            adapter.notifyDataSetChanged()
        }
        darkMode = DarkModeUtils.isDarkModeOn(context)
        _countAndKey = Pair(newSize, newKeys)
    }
}