package com.casic.electric.detector.base

import android.app.Application
import com.casic.electric.detector.greendao.DaoMaster
import com.casic.electric.detector.greendao.DaoSession
import com.casic.electric.detector.uart.SerialPort
import com.pengxh.kt.lite.utils.SaveKeyValues
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 serialPort: SerialPort? = null

    @Throws(SecurityException::class, IOException::class, InvalidParameterException::class)
    fun getSerialPort(): SerialPort? {
        if (serialPort == null) {
            /**
             * Open the serial port
             * */
            serialPort = SerialPort(File("/dev/ttysWK1"), 9600, 0)
        }
        return serialPort
    }

    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)
        val devOpenHelper = DaoMaster.DevOpenHelper(this, "ElectricDetector.db", null)
        val daoMaster = DaoMaster(devOpenHelper.writableDatabase)
        daoSession = daoMaster.newSession()
    }

    fun getDaoSession(): DaoSession {
        return daoSession
    }

    fun closeSerialPort() {
        if (serialPort != null) {
            serialPort?.close()
            serialPort = null
        }
    }
}