package com.develop.base.mvvm

import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.develop.base.ext.globalApp
import com.develop.base.scop.runOnMainThread

open class BaseFragment : Fragment() {
    lateinit var hostActivity: AppCompatActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)
        hostActivity = context as AppCompatActivity
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //是否拦截back事件，默认不拦截
        hostActivity.onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    if (shouldInterceptBackPress()) {
                        handleBackPressed()
                    } else {
                        if (hostActivity is BaseBindingActivity<*>) {
                            (hostActivity as BaseBindingActivity<*>).handleBackPress()
                        } else {
                            hostActivity.finish()
                        }
                    }
                }
            })
    }

    open fun shouldInterceptBackPress(): Boolean {
        return false
    }

    open fun handleBackPressed() {}

    private val viewModelProviderOfActivity: ViewModelProvider by lazy {
        ViewModelProvider(hostActivity)
    }
    private val viewModelProviderOfFragment: ViewModelProvider by lazy {
        ViewModelProvider(this)
    }

    fun <T : ViewModel> getViewModelOfActivity(type: Class<T>): T {
        return viewModelProviderOfActivity.get(type)
    }

    fun <T : ViewModel> getViewModelOfFragment(type: Class<T>): T {
        return viewModelProviderOfFragment.get(type)
    }


    fun showToast(message: String, duration: Int = Toast.LENGTH_SHORT) {
        val useContext = if (context == null) {
            globalApp()
        } else {
            requireContext()
        }
        runOnMainThread {
            Toast.makeText(useContext, message, duration).show()
        }
    }
}