package com.doverfuelingsolutions.issp.driver.lib

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.dto.DFSResult
import com.doverfuelingsolutions.issp.api.dto.ResultPayment
import com.doverfuelingsolutions.issp.driver.printer.ComPrintManager
import com.doverfuelingsolutions.issp.driver.printer.PrintStatusListen
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.utils.thread.ThreadUtil
import com.wayne.www.waynelib.fdc.message.DeviceClass
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class PrintManager : LifecycleObserver, PrintStatusListen {

    companion object {
        const val STATUS_FAIL_INIT = -1
    }

    private lateinit var comPrintManager: ComPrintManager

    private var callback: ((success: Boolean) -> Unit)? = null

    override fun receivePrintStatus(value: Int) {
        val success = value >= 0
        DFSLog.d("printer result: $success")
        callback?.invoke(success)
        callback = null
    }

    suspend fun print(dc: DeviceClass, posTrxBean: ResultPayment.PosTrxBean) = suspendCoroutine<DFSResult<Any>> {
        val manager = this
        ThreadUtil.io {
            if (!manager::comPrintManager.isInitialized) {
                try {
                    comPrintManager = ComPrintManager("/dev/ttyS3", 115200, this)
                } catch (e: Exception) {
                    DFSLog.e(e)
                    it.resume(DFSResult.fail(R.string.fail_init_printer))
                }
            }

            callback = { success ->
                it.resume(if (success) DFSResult.success(true) else DFSResult.fail(R.string.fail_print))
            }
            comPrintManager.printOrderOkBillHs(dc, posTrxBean)
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private fun create() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun destroy() {
        ThreadUtil.io {
            comPrintManager.destroy()
        }
    }
}