package com.dlc.chemical.serial.port.scan

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.view.KeyEvent
import com.dlc.chemical.serial.listener.OnSerialScanListener
import com.dlc.chemical.serial.usb.scan.ScanKeyEventHelper
import com.rc.core.log.RcLog
import com.rc.core.util.Weak

/**
 * info
 *
 * @author ReiChin_
 */
class PortScanHelper(context: Context, private val listener: OnSerialScanListener? = null) {

    private val mContext: Context? by Weak { context }

    private val mScanKeyEventHelper by lazy {
        ScanKeyEventHelper { content ->
            // RFID/IC 扫描返回
            RcLog.info("PortScanHelper#onReceive() RFID/IC content=${content}")
            listener?.dispatchScanEvent(OnSerialScanListener.ScanType.Rfid, content)
        }
    }

    fun dispatchKeyEvent(event: KeyEvent?) {
        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 扫描返回
                        val content = intent.getStringExtra("scan_content")!!
                        RcLog.info("PortScanHelper#onReceive() QRCode/IC content=${content}")
                        listener?.dispatchScanEvent(OnSerialScanListener.ScanType.QRCode, content)
                    }
                }

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

}