package com.swago.baseswago.fragment

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 *@date 2021/8/3 21:51
 *description:
 */
abstract class BaseFragment<T : ViewBinding> : Fragment(){

    private var _binding: T? = null
    val binding get() = _binding!!

    var mActivity: Activity? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as Activity
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = getViewBindingForFragment(inflater)
        return binding.root
    }

    @Suppress("UNCHECKED_CAST")
    fun getViewBindingForFragment(layoutInflater: LayoutInflater): T {
        val type = javaClass.genericSuperclass as ParameterizedType
        val aClass = type.actualTypeArguments[0] as Class<*>
        val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        return method.invoke(null, layoutInflater) as T
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
    
}