package com.casic.common.detector.gd.base

import android.app.Application
import com.casic.common.detector.gd.greendao.DaoMaster
import com.casic.common.detector.gd.greendao.DaoSession
import com.casic.common.detector.gd.uart.SerialPort
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.SaveKeyValues
import com.tencent.bugly.crashreport.CrashReport
import java.io.File
import java.io.IOException
import java.security.InvalidParameterException
import kotlin.properties.Delegates

class BaseApplication : Application() {

    private val kTag = "BaseApplication"
    private var serialPorts = ArrayList<SerialPort>()

    fun getSerialPorts(): ArrayList<SerialPort> = serialPorts

    fun closeSerialPort() {
        serialPorts.forEach {
            it.closeSerialPort()
        }
    }

    companion object {
        private var application: BaseApplication by Delegates.notNull()

        fun get() = application

        private lateinit var daoSession: DaoSession
    }

    override fun onCreate() {
        super.onCreate()
        application = this
        SaveKeyValues.initSharedPreferences(this)
        CrashReport.initCrashReport(this, "01e80d3a74", true)
        val devOpenHelper = DaoMaster.DevOpenHelper(this, "Detector.db", null)
        val daoMaster = DaoMaster(devOpenHelper.writableDatabase)
        daoSession = daoMaster.newSession()

        /**
         * Open the serial port
         * */
        try {
            serialPorts.apply {
                add(SerialPort(File("/dev/ttysWK1"), 9600, 0))
                add(SerialPort(File("/dev/ttysWK2"), 9600, 0))
                //千寻报文数据下发串口号
                add(SerialPort(File("/dev/ttyS1"), 9600, 0))
            }
        } catch (e: SecurityException) {
            "您没有串口的读写权限！".show(this)
        } catch (e: IOException) {
            "因为不明原因，串口无法打开！".show(this)
        } catch (e: InvalidParameterException) {
            "请检查串口！".show(this)
        }
    }

    fun getDaoSession(): DaoSession {
        return daoSession
    }
}