package com.dlc.chemical.sp

import android.content.Context
import com.dlc.chemical.serial.port.scan.PortScanManager
import java.lang.Exception

/**
 * info
 *
 * @author ReiChin_
 */
object PortDevicesSp {

    private const val SP_NAME = "port_devices_sp"
    private const val KEY_PATH = "_path"
    private const val KEY_BAUD_RATE = "_baud_rate"

    fun saveConfig(
        context: Context,
        config: PortDevicesConfig,
        type: PortDevicesType = PortDevicesType.SCAN
    ) {
        saveConfig(context, config.path, config.baudRate, type)
    }

    fun saveConfig(
        context: Context,
        path: String,
        baudRate: Int,
        type: PortDevicesType = PortDevicesType.SCAN
    ) {
        val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
        sp.edit()
            .putString("${type.name}${KEY_PATH}", path)
            .putInt("${type.name}${KEY_BAUD_RATE}", baudRate)
            .apply()
    }

    fun loadConfig(
        context: Context,
        type: PortDevicesType = PortDevicesType.SCAN,
        defPath: String = PortScanManager.PATH,
        defBaudRate: Int = PortScanManager.BAUD_RATE
    ): PortDevicesConfig {
        return try {
            val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
            val path = sp.getString("${type.name}${KEY_PATH}", defPath)!!
            val baudRate = sp.getInt("${type.name}${KEY_BAUD_RATE}", defBaudRate)
            PortDevicesConfig(path = path, baudRate = baudRate)
        } catch (e: Exception) {
            e.printStackTrace()
            PortDevicesConfig(path = defPath, baudRate = defBaudRate)
        }
    }

}

data class PortDevicesConfig(val path: String, val baudRate: Int)

enum class PortDevicesType {
    SCAN
}