package com.gh.common.dialog

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.gh.gamecenter.common.HaloApp
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.DialogFragmentAcceleratorPermissionGuideBinding

class AcceleratorPermissionGuideDialogFragment : BaseDialogFragment() {

    private lateinit var binding: DialogFragmentAcceleratorPermissionGuideBinding

    private var callback: (() -> Unit)? = null

    override fun onBack(): Boolean {
        return true
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return DialogFragmentAcceleratorPermissionGuideBinding.inflate(inflater, container, false)
            .also {
                binding = it
            }.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        SPUtils.setBoolean(Constants.SP_ACCELERATOR_PERMISSION_GUIDE_SHOW, true)
        binding.tvSubmit.setOnClickListener {
            dismiss()
            callback?.invoke()
        }
    }

    fun setOnCallback(block: () -> Unit) {
        this.callback = block
    }

    override fun onStart() {
        super.onStart()
        val width = HaloApp.getInstance().resources.displayMetrics.widthPixels - 60F.dip2px()
        val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    companion object {

        fun show(context: Context, callback: () -> Unit) {
            if (context is AppCompatActivity) {
                context.supportFragmentManager
            } else {
                (CurrentActivityHolder.getCurrentActivity() as? AppCompatActivity)?.supportFragmentManager
            }?.let {
                val fragment = AcceleratorPermissionGuideDialogFragment()
                fragment.setOnCallback(callback)
                fragment.show(it, AcceleratorPermissionGuideDialogFragment::class.java.name)
            }
        }
    }
}