package com.tools.device.devcheck.base

import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
import com.tools.device.devcheck.databinding.DialogBaseBinding

abstract class BaseDialogFragment<VB : ViewBinding>(
    private val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : DialogFragment() {

    private var _binding: DialogBaseBinding? = null
    private val baseBinding get() = _binding!!
    private var _contentBinding: VB? = null
    protected val binding get() = _contentBinding!!

    abstract fun getTitle(): String
    open fun getIconRes(): Int? = null


    open fun onPositiveClick() {}
    open fun onNegativeClick() {}

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = DialogBaseBinding.inflate(inflater, container, false)

        // inflate 子类内容到 contentContainer
        _contentBinding = bindingInflater(inflater, baseBinding.contentContainer, true)

        return baseBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        baseBinding.dialogTitle.text = getTitle()
        getIconRes()?.let {
            baseBinding.imageIcon.setImageResource(it)
            baseBinding.imageIcon.visibility = View.VISIBLE
        }
        baseBinding.textCancel.setOnClickListener {
            onPositiveClick()
            dismiss()
        }
        baseBinding.textSettings.setOnClickListener {
            onNegativeClick()
            dismiss()
        }
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.let { window ->
            window.setBackgroundDrawable(Color.TRANSPARENT.toDrawable())

            val params = window.attributes
            val displayMetrics = resources.displayMetrics
            val margin = (10 * displayMetrics.density).toInt()
            params.width = displayMetrics.widthPixels - margin * 2
            params.height = WindowManager.LayoutParams.WRAP_CONTENT
            window.attributes = params
            window.setGravity(Gravity.CENTER)
        }
    }

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


