package com.doverfuelingsolutions.testdemo.driver.lib

import com.doverfuelingsolutions.testdemo.driver.scan.ComScanKeyManager
import com.doverfuelingsolutions.testdemo.driver.scan.ScanValueListener
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class ScanCodeManager : ScanValueListener {

    private lateinit var comScanKeyManager: ComScanKeyManager
    val isAvailable: Boolean get() = isInit
    private var isInit = false

    private var callback: ((v: String?) -> Unit)? = null

    override fun onScanValue(value: String?) {
        callback?.invoke(value)
        callback = null
    }

    suspend fun start() = suspendCoroutine<String?> {
        Thread {
            if (!isInit) {
                it.resume(null)
                return@Thread
            }

            comScanKeyManager.start()
            callback = { v -> it.resume(v) }
        }.start()
    }

    fun stop() {
        Thread {
            comScanKeyManager.stop()
        }.start()
    }

    suspend fun create() = suspendCoroutine<Boolean> {
        if (isInit) {
            it.resume(true)
            return@suspendCoroutine
        }

        Thread {
            try {
                comScanKeyManager = ComScanKeyManager("/dev/ttyACM0", 115200, this)
                isInit = true
            } catch (e: Exception) {
                isInit = false
            }
            it.resume(isInit)
        }.start()
    }

    fun destroy() {
        isInit = false
        Thread {
            comScanKeyManager.stop()
            comScanKeyManager.destroy()
        }.start()
    }
}