package com.xuqm.base.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment

class AlertDialogFragment : DialogFragment() {
    companion object {
        fun newInstance(
            title: String,
            message: String,
            confirm: String,
            cancel: String
        ): AlertDialogFragment {
            val args = Bundle()
            args.putString("title", title)
            args.putString("message", message)
            args.putString("confirm", confirm)
            args.putString("cancel", cancel)
            val fragment = AlertDialogFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var title: String? = null
    private var message: String? = null
    private var confirm: String? = null
    private var cancel: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        title = arguments?.getString("title")
        message = arguments?.getString("message")
        confirm = arguments?.getString("confirm")
        cancel = arguments?.getString("cancel")
    }


    private lateinit var listener: NoticeDialogListener

    interface NoticeDialogListener {
        fun onDialogPositiveClick(dialog: DialogFragment)
        fun onDialogNegativeClick(dialog: DialogFragment)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        try {
            listener = context as NoticeDialogListener
        } catch (e: ClassCastException) {
            throw ClassCastException(
                (context.toString() +
                        " must implement NoticeDialogListener")
            )
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val builder = AlertDialog.Builder(it)
            title?.let { it1 -> builder.setTitle(it1) }
            message?.let { it1 -> builder.setMessage(it1) }
            confirm?.let { it1 ->
                builder.setPositiveButton(
                    it1
                ) { _, _ ->
                    listener.onDialogPositiveClick(this)
                }
            }
            cancel?.let { it1 ->
                builder.setNegativeButton(
                    it1
                ) { _, _ ->
                    listener.onDialogNegativeClick(this)
                }
            }
            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }

}