package com.gh.gamecenter.common.base.fragment

import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.utils.getSuperClassGenericType
import com.gh.gamecenter.core.utils.DisplayUtils

/**
 * @author : liujiarui
 * date : 2023/3/20
 * description : 底部弹出dialog
 */
abstract class BaseBottomDialogFragment<T : ViewBinding> : BaseDialogFragment() {

    protected lateinit var mBinding: T

    private fun initViewBinding(inflater: LayoutInflater): T {
        return this::class.java.getSuperClassGenericType<T>().getMethod(
            "inflate",
            LayoutInflater::class.java,
            ViewGroup::class.java,
            Boolean::class.java
        ).invoke(null, inflater, null, false) as T
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        initViewBinding(inflater).apply { mBinding = this }
        return mBinding.root
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val createDialog = super.onCreateDialog(savedInstanceState)
        createDialog.setCanceledOnTouchOutside(true)
        val window = createDialog.window
        window?.setGravity(Gravity.BOTTOM)
        window?.setWindowAnimations(R.style.community_publication_animation)
        return createDialog
    }

    override fun onStart() {
        super.onStart()
        val width = if (isWidthMatchParent()) DisplayUtils.getScreenWidth(activity) else {
            dialog?.window?.attributes?.width ?: ViewGroup.LayoutParams.WRAP_CONTENT
        }
        val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    /**
     * 是否宽度撑满屏幕
     */
    protected fun isWidthMatchParent(): Boolean {
        return true
    }
}