package com.dlc.eboard.serial

import android.content.*
import android.os.IBinder
import android.view.KeyEvent
import com.rc.core.log.RcLog
import com.rc.core.util.Weak

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

    private val mContext: Context? by Weak { context }

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

    fun dispatchKeyEvent(event: KeyEvent?) {
        event?.let { mScanKeyEventHelper.analysisKeyEvent(it) }
    }

    private var mSerialBinder: SerialPortService.SerialBinder? = null

    private val mSerialConnection: ServiceConnection = object : ServiceConnection {

        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            mSerialBinder = service as SerialPortService.SerialBinder
            listener?.onServiceConnected()
        }

        override fun onServiceDisconnected(name: ComponentName) {
        }
    }

    fun bindService() {
        mContext?.let { context ->
            val intent = Intent(context, SerialPortService::class.java)
            context.bindService(intent, mSerialConnection, Context.BIND_AUTO_CREATE)
        }
    }

    fun unbindService() {
        mContext?.unbindService(mSerialConnection)
    }

    fun openDoor() {
        mSerialBinder?.openDoor()
    }

    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(SerialPortService.ACTION_PORT_SCAN)
            mScanBroadcastReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    if (SerialPortService.ACTION_PORT_SCAN == intent?.action) {
                        // QRCode/IC 扫描返回
                        val content = intent.getStringExtra("scan_content")!!
                        RcLog.info("SerialPortHelper#onReceive() PORT content=${content}")
                        listener?.dispatchScanEvent(OnSerialScanListener.ScanType.PORT, content)
                    }
                }

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

}