package com.yidian.bcommon.mvvm.delegate

import android.view.LayoutInflater
import android.view.View
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.yidian.bcommon.BR
import com.yidian.bcommon.mvvm.BaseMvvmActivity
import com.yidian.bcommon.mvvm.BaseMvvmFragment
import com.yidian.bcommon.mvvm.BaseViewModel
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty


class ActivityDataBindingDelegate<in activity : AppCompatActivity, out T : ViewDataBinding>(
  @LayoutRes private val layoutRes: Int,
) : ReadOnlyProperty<activity, T> {

  override fun getValue(thisRef: activity, property: KProperty<*>): T {
    val contentView: View = thisRef.layoutInflater.inflate(layoutRes, null)
    val dataBinding: T = DataBindingUtil.bind<T>(contentView)!!
    thisRef.lifecycle.addObserver(object : LifecycleObserver {
      @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
      fun onCreate() {
        dataBinding.lifecycleOwner = thisRef
        thisRef.setContentView(layoutRes)
      }
    })
    return dataBinding
  }
}

fun <V : ViewDataBinding, VM : BaseViewModel> BaseMvvmActivity<V, VM>.viewBindings(@LayoutRes layoutRes: Int, vm: VM?):V {
  val dataBinding = DataBindingUtil.setContentView<V>(this, layoutRes)
  dataBinding.lifecycleOwner = this
  vm?.let {
    dataBinding.setVariable(BR.vm, vm)
  }
  return dataBinding
}

fun <V : ViewDataBinding, VM : BaseViewModel> BaseMvvmFragment<V, VM>.viewBindings(@LayoutRes layoutRes: Int, vm: VM?):V {
  val inflater: LayoutInflater = this.layoutInflater
  val dataBinding = DataBindingUtil.inflate<V>(inflater, layoutRes,null,false)
  dataBinding.lifecycleOwner = this.viewLifecycleOwner
  vm?.let {
    dataBinding.setVariable(BR.vm, vm)
  }
  return dataBinding
}
