package com.casic.detector.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.pengxh.kt.lite.extensions.show
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.OutputStream
import java.security.InvalidParameterException


abstract class SerialPortActivity<VB : ViewBinding> : AppCompatActivity() {

    protected lateinit var binding: VB

    lateinit var out: OutputStream

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = initViewBinding()
        setContentView(binding.root)
        setupTopBarLayout()
        initOnCreate(savedInstanceState)
        observeRequestState()
        initEvent()

        try {
            val serialPorts = BaseApplication.get().getSerialPorts()
            //读
            lifecycleScope.launch(Dispatchers.IO) {
                serialPorts?.apply {
                    val stream = this[0].inputStream
                    while (isActive) {
                        try {
                            val buffer = ByteArray(64)
                            val size = stream.read(buffer)
                            if (size > 0) {
                                withContext(Dispatchers.Main) {
                                    onDataReceived(buffer)
                                }
                            }
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            lifecycleScope.launch(Dispatchers.IO) {
                serialPorts?.apply {
                    val stream = this[1].inputStream
                    while (isActive) {
                        try {
                            val buffer = ByteArray(64)
                            val size = stream.read(buffer)
                            if (size > 0) {
                                withContext(Dispatchers.Main) {
                                    onDataReceived(buffer)
                                }
                            }
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            //写
            serialPorts?.apply {
                out = this[0].outputStream
            }
        } catch (e: SecurityException) {
            "您没有串口的读写权限！".show(this)
        } catch (e: IOException) {
            "因为不明原因，串口无法打开！".show(this)
        } catch (e: InvalidParameterException) {
            "请检查串口！".show(this)
        }
    }

    /**
     * 初始化ViewBinding
     */
    abstract fun initViewBinding(): VB

    /**
     * 特定页面定制沉浸式状态栏
     */
    abstract fun setupTopBarLayout()

    /**
     * 初始化默认数据
     */
    abstract fun initOnCreate(savedInstanceState: Bundle?)

    /**
     * 数据请求状态监听
     */
    abstract fun observeRequestState()

    /**
     * 初始化业务逻辑
     */
    abstract fun initEvent()

    /**
     * 串口读数，已经切回主线程
     * */
    abstract fun onDataReceived(buffer: ByteArray)

    override fun onDestroy() {
        BaseApplication.get().closeSerialPort()
        super.onDestroy()
    }
}