package com.dlc.eboard.serial

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import com.rc.core.log.RcLog

/**
 * info
 *
 * @author ReiChin_
 */
class SerialPortService: Service(), OnSerialListener {

    companion object {
        const val ACTION_PORT_SCAN = "com.dlc.eboard.serial:PORT_SCAN"
    }

    private val mBinder by lazy {
        SerialBinder()
    }

    override fun onBind(intent: Intent?): IBinder {
        return mBinder
    }

    inner class SerialBinder : Binder() {

        fun openDoor() {
            mPortScanManager.sendHex(SerialPortManager.CMD_OPEN)
        }
    }

    override fun onCreate() {
        super.onCreate()
        mPortScanManager.connect(this)
    }

    private val mPortScanManager by lazy {
        SerialPortManager(this)
    }

    override fun onDestroy() {
        mPortScanManager.disconnect()
        super.onDestroy()
    }

    override fun onConnected(success: Boolean, message: String?) {
        RcLog.info("SerialPortService#onConnected() success=${success}, message=${message}")
    }

    override fun onReceive(content: String) {
        // QRCode/IC 扫描返回
        RcLog.info("SerialPortService#onReceive() QRCode/IC content=${content}")
        val intent = Intent().apply {
            putExtra("scan_content", content)
            action = ACTION_PORT_SCAN
        }
        sendBroadcast(intent)
    }

}