package com.lukouguoji.module_base.base

import android.content.Intent
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.lukouguoji.module_base.BaseActivity
import kotlin.properties.Delegates

abstract class BaseBindingActivity<T : ViewDataBinding, VM : ViewModel> : BaseActivity() {

    //视图绑定器
    protected var binding: T by Delegates.notNull()

    //ViewModel
    protected val viewModel: VM by lazy {
        ViewModelProvider(this).get(viewModelClass())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //dataBinding初始化
        binding = DataBindingUtil.setContentView(this, layoutId())
        binding.lifecycleOwner = this

        initOnCreate(savedInstanceState)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (viewModel is BaseViewModel) {
            (viewModel as BaseViewModel).onActivityResult(requestCode, resultCode, data)
        }
    }

    /**
     * 布局ID
     */
    abstract fun layoutId(): Int

    /**
     * ViewModel类
     */
    abstract fun viewModelClass(): Class<VM>

    /**
     * 初始化Activity内容
     */
    abstract fun initOnCreate(savedInstanceState: Bundle?)

    fun requireActivity() = this
    fun requireContext() = this

}