package com.adealink.weparty.commonui.recycleview.adapter.multitype

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView

/**
 */
abstract class ExtItemViewBinder<T, VH : RecyclerView.ViewHolder>(private val lifecycleOwner: LifecycleOwner) :
    ItemViewDelegate<T, VH>() {

    final override fun onCreateViewHolder(context: Context, parent: ViewGroup): VH {
        val holder = onCreateViewHolder(LayoutInflater.from(context), parent)

        lifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onResume(owner: LifecycleOwner) {
                if (holder.itemView.isAttachedToWindow) {
                    onResume(holder = holder)
                }
            }

            override fun onStop(owner: LifecycleOwner) {
                if (holder.itemView.isAttachedToWindow) {
                    onStop(holder = holder)
                }
            }

            override fun onDestroy(owner: LifecycleOwner) {
                lifecycleOwner.lifecycle.removeObserver(this)
            }
        })
        return holder
    }

    abstract fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): VH


    open fun onResume(holder: VH) {}

    open fun onStop(holder: VH) {}

}