package xn.hxp.weidith

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.InputFilter
import android.view.Gravity
import android.view.KeyEvent
import android.view.Window
import android.view.WindowManager
import android.widget.Button
import android.widget.EditText
import xn.hxp.R

//化学品标签--气瓶标签提示
class AirBottleDialog(private val ct: Context, private val lintDate: ILintDate) : Dialog(ct) {

    init {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.air_bottle_dialog)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window?.setGravity(Gravity.CENTER)
        window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
        setCanceledOnTouchOutside(false)
        setCancelable(false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 禁止EditText中输入换行符
        val editText = findViewById<EditText>(R.id.cont)
        editText?.filters = arrayOf(InputFilter { source, _, _, _, _, _ ->
            if (source.contains("\n") || source.contains("\r")) source.replace(Regex("[\n\r]"), "") else null
        })
        editText?.setSingleLine(true)

        findViewById<Button>(R.id.butClos).setOnClickListener {
            dismiss()
        }

        findViewById<Button>(R.id.butDetermine).setOnClickListener {
            val trim = findViewById<EditText>(R.id.cont).text.toString().trim()
            if (trim.isEmpty()) {
                return@setOnClickListener
            } else {
                lintDate.onLintDate(trim)
                dismiss()
            }
        }
    }

    interface ILintDate {
        fun onLintDate(cont: String)
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        // 只拦截外部设备的ENTER键，其他字符正常传入EditText
        if (event.device != null && event.device.isExternal
            && (event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) {
            return true
        }
        return super.dispatchKeyEvent(event)
    }
}
