package com.dlc.chemical.ui.dialog

import android.app.Dialog
import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.Toast
import com.dlc.chemical.R
import com.dlc.chemical.common.CommonUtils
import com.dlc.chemical.databinding.DialogInputWeightBinding
import com.rc.core.util.trimEndZero
import java.util.regex.Pattern

/**
 * info
 *
 * @author ReiChin_
 */
class InputWeightDialog(
    context: Context,
    private val chemicalUnit: String = "g",
    private val dialogListener: ((weight: String) -> Unit)? = null
) :
    Dialog(context, R.style.AlertDialogStyle) {

    private val viewBinding: DialogInputWeightBinding by lazy {
        DialogInputWeightBinding.inflate(LayoutInflater.from(context))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(viewBinding.root)
        initWindowConfig()
        initViews()
    }

    private fun initWindowConfig() {
        window?.apply {
            val dm = Resources.getSystem().displayMetrics
            attributes.width = (dm.widthPixels * 0.32f).toInt()
            attributes.height = WindowManager.LayoutParams.WRAP_CONTENT
        }
    }

    private fun initViews() {
        // 取消
        viewBinding.cancel.setOnClickListener { dismiss() }
        // 确认
        viewBinding.confirm.setOnClickListener {
            val weight = viewBinding.input.text.toString().trim()
            val regex = "^(?:0|[1-9]\\d*)(?:\\.\\d{0,5})?$"
            if (weight.isEmpty()
                || !Pattern.matches(regex, weight)
                || CommonUtils.stringParseFloat(weight) <= 0
            ) {
                Toast.makeText(context, "请输入有效的重量！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            dialogListener?.invoke(weight.trimEndZero())
            dismiss()
        }
        viewBinding.input.hint = "输入重量，单位：${chemicalUnit}"
    }

}