package com.dlc.chemical.sp

import android.content.Context
import com.dlc.chemical.serial.usb.steelyard.SteelyardManager
import java.lang.Exception

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

    private const val SP_NAME = "usb_devices_sp"
    private const val KEY_VID = "_vid"
    private const val KEY_PID = "_pid"

    fun saveConfig(
        context: Context,
        config: UsbDevicesConfig,
        type: UsbDevicesType = UsbDevicesType.STEELYARD
    ) {
        saveConfig(context, config.vendorId, config.productId, type)
    }

    fun saveConfig(
        context: Context,
        vendorId: Int,
        productId: Int,
        type: UsbDevicesType = UsbDevicesType.STEELYARD
    ) {
        val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
        sp.edit()
            .putInt("${type.name}${KEY_VID}", vendorId)
            .putInt("${type.name}${KEY_PID}", productId)
            .apply()
    }

    fun loadConfig(
        context: Context,
        type: UsbDevicesType = UsbDevicesType.STEELYARD,
        defVID: Int = SteelyardManager.DEVICE_VID,
        defPID: Int = SteelyardManager.DEVICE_PID
    ): UsbDevicesConfig {
        return try {
            val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
            val vendorId = sp.getInt("${type.name}${KEY_VID}", defVID)
            val productId = sp.getInt("${type.name}${KEY_PID}", defPID)
            UsbDevicesConfig(vendorId = vendorId, productId = productId)
        } catch (e: Exception) {
            e.printStackTrace()
            UsbDevicesConfig(vendorId = defVID, productId = defPID)
        }
    }

}

data class UsbDevicesConfig(val vendorId: Int, val productId: Int)

enum class UsbDevicesType {
    STEELYARD
}