package com.ydl.ydlcommon.ui


import android.os.Bundle
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import com.ydl.ydlcommon.R
import kotlinx.android.synthetic.main.platform_fragment_loading_dialog.view.*


/**
 * A simple [Fragment] subclass.
 * Use the [LoadingDialogFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class LoadingDialogFragment : DialogFragment() {

    private var msg: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
            msg = arguments?.getString(ARG_MSG)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        return inflater.inflate(R.layout.platform_fragment_loading_dialog, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (!TextUtils.isEmpty(msg)) {
            view.tvMsg.text = msg
        } else {
            view.tvMsg.visibility = View.GONE
        }
    }

    companion object {
        private val ARG_MSG = "arg_msg"
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param msg 要显示的信息.
         * @return  LoadingDialogFragment 实例
         */
        fun newInstance(msg: String?): LoadingDialogFragment {
            val fragment = LoadingDialogFragment()
            val args = Bundle()
            args.putString(ARG_MSG, msg)
            fragment.arguments = args
            return fragment
        }
    }

    override fun show(manager: FragmentManager, tag: String?) {
        try {
            //在每个add事务前增加一个remove事务，防止连续的add
            manager.beginTransaction().remove(this).commitAllowingStateLoss()
            super.show(manager, tag)
        } catch (e: Exception) {
            //同一实例使用不同的tag会异常,这里捕获一下
            e.printStackTrace()
        }
    }

    fun hide() {
        dismissAllowingStateLoss()
    }
}
