package com.miya.fastcashier.log

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * 作者：Leon
 * 时间：2017/3/17 13:44
 */
class EmptyRecyclerView : RecyclerView {

    private var mEmptyView: View? = null

    constructor(context: Context?) : super(context!!) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(
        context!!, attrs
    ) {
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context!!, attrs, defStyle
    ) {
    }

    /**
     * 根据数据源判断是否显示空白view
     */
    private fun checkIfEmpty() {
        if (mEmptyView != null || adapter != null) {
            mEmptyView!!.visibility =
                if (adapter!!.itemCount > 0) GONE else VISIBLE
        }
    }

    fun setmEmptyView(mEmptyView: View?) {
        this.mEmptyView = mEmptyView
        checkIfEmpty()
    }

    override fun setAdapter(adapter: Adapter<*>?) {
        val adapterOld = getAdapter()
        adapterOld?.unregisterAdapterDataObserver(observer)
        super.setAdapter(adapter)
        adapter?.registerAdapterDataObserver(observer)
    }

    var observer: AdapterDataObserver = object : AdapterDataObserver() {
        override fun onChanged() {
            super.onChanged()
            checkIfEmpty()
        }
    }
}