package xn.hxp.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.view.KeyEvent
import com.blankj.utilcode.util.LogUtils
import com.rc.core.util.Weak

class PortScanHelper (context: Context, private val listener: OnSerialScanListener? = null) {

    private val mContext: Context? by Weak { context }

    private val mScanKeyEventHelper by lazy {
        ScanKeyEventHelper { content ->
            //   扫描返回
            listener?.dispatchScanEvent(OnSerialScanListener.ScanType.Rfid, content)
        }
    }

    fun dispatchKeyEvent(event: KeyEvent?) {
//        LogUtils.i("PortScanHelper#dispatchKeyEvent2222=======")
        event?.let {
            mScanKeyEventHelper.analysisKeyEvent(it)
        }
    }

    fun onPause() {
        mScanBroadcastReceiver?.let {
            mContext?.unregisterReceiver(it)
        }
        mScanBroadcastReceiver = null
    }

    fun onResume() {
        registerScanBroadcastReceiver()
    }

    private var mScanBroadcastReceiver: BroadcastReceiver? = null

    private fun registerScanBroadcastReceiver() {
        if (null == mScanBroadcastReceiver) {
            val filter = IntentFilter(PortScanService.ACTION_PORT_SCAN)
            mScanBroadcastReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    if (PortScanService.ACTION_PORT_SCAN == intent?.action) {
                        // QRCode/IC or RFID 扫描返回
                        val content = intent.getStringExtra("scan_content")!!


                        val octNum = isOctNum(content)
                        LogUtils.i("=============isOctNum=====${octNum}")
                        if (isOctNum(content)) {//RFID
                            listener?.dispatchScanEvent(OnSerialScanListener.ScanType.Rfid, content)
                        } else {
                            listener?.dispatchScanEvent(
                                OnSerialScanListener.ScanType.QRCode,
                                content
                            )
                        }
                    }
                }

            }
            mContext?.registerReceiver(mScanBroadcastReceiver, filter)
        }
    }

    private fun isOctNum(str: String): Boolean {
        return try {
            str.toDouble()
            true
        } catch (nbFmtExp: NumberFormatException) {
            false
        }
    }
}