package com.abbidot.tracker.base

import androidx.recyclerview.widget.DiffUtil

/**
 *Created  by .yzq on 2021/11/12/012.
 * @link
 * @description: DiffUtil基类封装
 */
open class BaseDiffCallBack<T>(oldList: MutableList<T>?, newList: MutableList<T>?) :
    DiffUtil.Callback() {

    private var mOldList: MutableList<T>? = oldList
    private var mNewList: MutableList<T>? = newList

    override fun getOldListSize() = if (mOldList == null) {
        0
    } else mOldList!!.size

    override fun getNewListSize() = if (mNewList == null) {
        0
    } else mNewList!!.size

    /**
     * 判断新旧item是否是同一个item，最好以唯一不变的id作比较
     */
    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
//        if (null == mNewList || null == mOldList) return false
        val newItem = mNewList!![newItemPosition]
        if (newItem is BaseDiffBean) {
            return newItem.isSameObject(mOldList!![oldItemPosition]!!)
        }
        return true
    }

    /**
     * 是同一个item。然后比较新旧item的内容是否一样
     */
    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        val newItem = mNewList!![newItemPosition]
        if (newItem is BaseDiffBean) {
            return newItem.hasSameContent(mOldList!![oldItemPosition]!!)
        }
        return false
    }

    /**
     * 局部刷新比较，只更新某个item
     */
    override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
        val newDeviceBean = mNewList?.get(newItemPosition)
        if (!areContentsTheSame(oldItemPosition, newItemPosition)) {
            return newDeviceBean
        }
        return null
    }
}