package com.casic.detector.base

import android.app.Application
import com.casic.detector.greendao.DaoMaster
import com.casic.detector.greendao.DaoSession
import com.casic.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 serialPorts: ArrayList<SerialPort>? = null

    @Throws(SecurityException::class, IOException::class, InvalidParameterException::class)
    fun getSerialPorts(): ArrayList<SerialPort>? {
        serialPorts = ArrayList()
        /**
         * Open the serial port
         * */
        serialPorts?.apply {
            add(SerialPort(File("/dev/ttysWK1"), 9600, 0))
            add(SerialPort(File("/dev/ttysWK2"), 9600, 0))
        }
        return serialPorts
    }


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

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

    fun getDaoSession(): DaoSession {
        return daoSession
    }
}