package com.reactnativerfidble.adapters

import com.facebook.react.bridge.ReactApplicationContext
import com.reactnativerfidble.generic.RfidBleGenericEpcReply
import com.rscja.deviceapi.RFIDWithUHFBLE

class RfidBleU909Adapter(
    reactContext: ReactApplicationContext
) : RfidBleAdapter(reactContext) {
    companion object {
        /**
         *
         */
        const val TAG_READ_DELAY = 1L
    }

    private val uhf = RFIDWithUHFBLE.getInstance()
    private var runningThread = false

    init {
        // Initialize services
        uhf.init(reactContext.applicationContext)

        // Listen for gun shooting (main button pulsation)
        uhf.setKeyEventCallback {
            runningThread = if (runningThread) {
                false
            } else {
                TagThread().start()
                true
            }
        }
    }

    override fun connectToReader(readerAddress: String) {
        uhf.connect(readerAddress)
    }

    override fun disconnect() {
        runningThread = false
        uhf.disconnect()
    }

    inner class TagThread : Thread() {
        override fun run() {
            uhf.startInventoryTag()

            while (runningThread) {
                val epcList = uhf.readTagFromBufferList()

                if (epcList == null || epcList.isEmpty()) {
                    sleep(TAG_READ_DELAY)
                } else {
                    emitBleEpcReplies(
                        "U909",
                        epcList,
                        fun(reply) = RfidBleGenericEpcReply(reply.epc)
                    )
                }
            }

            uhf.stopInventory()
        }
    }
}