package mtp.polymer.com.autowidget.dialog

import android.os.Bundle

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.DialogFragment
import cn.muchinfo.rma.view.autoWidget.onThrottleFirstClick
import org.jetbrains.anko._FrameLayout

class CustomDialogFragment : AppCompatDialogFragment() {

    companion object {
        fun createInstance(appCompatActivity: AppCompatActivity, createView: (_FrameLayout.(CustomDialogFragment) -> View)): CustomDialogFragment {
            return CustomDialogFragment().apply {
                this.appCompatActivity = appCompatActivity
                this.createViewBlock = createView
            }
        }
    }

    private lateinit var appCompatActivity: AppCompatActivity
    private var createViewBlock: (_FrameLayout.(CustomDialogFragment) -> View)? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_FRAME, android.R.style.Theme_Translucent_NoTitleBar)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return _FrameLayout(appCompatActivity).apply {
            createViewBlock?.invoke(this, this@CustomDialogFragment)
            onThrottleFirstClick {
                if (isCancelable) {
                    dismiss()
                }
            }
        }
    }

    fun show() {
        appCompatActivity.let { activity ->
            show(activity.supportFragmentManager, javaClass.name)
        }
    }
}