package com.adealink.weparty.commonui.widget

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnWindowFocusChangeListener
import android.view.WindowManager
import androidx.annotation.LayoutRes
import com.adealink.frame.util.fitDialogEdgeToEdge
import com.adealink.weparty.R
import com.adealink.weparty.commonui.dialogfragment.BaseDialogFragment

abstract class BottomDialogFragment(@LayoutRes override val layoutId: Int) :
    BaseDialogFragment(layoutId) {

    companion object {
        private const val TAG = "BottomDialogFragment"
    }

    open val dimAmount: Float = 0.2F
    open val followActivityUIFlag: Boolean = false
    open val height = ViewGroup.LayoutParams.WRAP_CONTENT

    private val windowFocusChangeListener = object: OnWindowFocusChangeListener {
        override fun onWindowFocusChanged(hasFocus: Boolean) {
            //有的手机在获取焦点后会重新展示底部导航条，再次调用进行全面屏设置
            takeIf { hasFocus }?.runCatching { fitDialogEdgeToEdge(context, dialog, view)}
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.BottomDialog)
    }

    override fun onStart() {
        super.onStart()
        setDialogAttributes(height)
    }

    open fun setDialogAttributes(height: Int) {
        try {
            fitDialogEdgeToEdge(context, dialog, view)
            view?.viewTreeObserver?.apply {
                removeOnWindowFocusChangeListener(windowFocusChangeListener)
                addOnWindowFocusChangeListener(windowFocusChangeListener)
            }
            val dialog: Dialog = dialog ?: return
            dialog.window!!.setLayout(
                ViewGroup.LayoutParams.MATCH_PARENT,
                height
            )
            dialog.window!!.setGravity(Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM)
            val windowParams = dialog.window?.attributes
            windowParams?.dimAmount = dimAmount
            dialog.window?.attributes = windowParams
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }

    @SuppressLint("RestrictedApi")
    override fun setupDialog(dialog: Dialog, style: Int) {
        super.setupDialog(dialog, style)
        // Make the dialog non-focusable before showing it
        if (followActivityUIFlag && dialog.window != null) {
            dialog.window!!.setFlags(
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            )
        }
    }

}
