package com.dlc.eboard.sp

import android.content.Context
import com.dlc.eboard.common.Constants
import java.lang.Exception

/**
 * 环境相关
 *
 * @author ReiChin_
 */
object EnvSp {

    private const val SP_NAME = "lab_env"
    private const val KEY_BASE_URL = "base_url"
    private const val KEY_SIGN_IN_CHECK_BASE_URL = "sign_in_check_base_url"
    private const val KEY_MQTT_SERVER_URI = "mqtt_server_uri"
    private const val KEY_MQTT_U_NAME = "mqtt_u_name"
    private const val KEY_MQTT_U_PWD = "mqtt_u_pwd"
    private const val KEY_SETTING_PWD = "setting_pwd"
    private const val KEY_API_VERSION = "api_version"

    fun saveEnv(context: Context, envConfig: EnvConfig) {
        val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
        sp.edit()
            .putString(KEY_BASE_URL, envConfig.baseUrl)
            .putString(KEY_SIGN_IN_CHECK_BASE_URL, envConfig.signInCheckBaseUrlSp)
            .putString(KEY_MQTT_SERVER_URI, envConfig.mqttServerUri)
            .putString(KEY_MQTT_U_NAME, envConfig.mqttUName)
            .putString(KEY_MQTT_U_PWD, envConfig.mqttUPwd)
            .putString(KEY_SETTING_PWD, envConfig.settingPwd)
            .putInt(KEY_API_VERSION, envConfig.apiVersion)
            .apply()
    }

    fun loadEnv(context: Context): EnvConfig? {
        return try {
            val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
            val baseUrl = sp.getString(KEY_BASE_URL, null)
            val signInCheckBaseUrlSp = sp.getString(KEY_SIGN_IN_CHECK_BASE_URL, null)
            val mqttServerUri = sp.getString(KEY_MQTT_SERVER_URI, null)
            val mqttUName = sp.getString(KEY_MQTT_U_NAME, null)
            val mqttUPwd = sp.getString(KEY_MQTT_U_PWD, null)
            val settingPwd = sp.getString(KEY_SETTING_PWD, null)
            val apiVersion = sp.getInt(KEY_API_VERSION, Constants.NetExtra.API_VERSION)
            EnvConfig(baseUrl, signInCheckBaseUrlSp, mqttServerUri, mqttUName, mqttUPwd, settingPwd, apiVersion)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

}

data class EnvConfig(
    val baseUrl: String?,
    val signInCheckBaseUrlSp: String?,
    val mqttServerUri: String?,
    val mqttUName: String?,
    val mqttUPwd: String?,
    val settingPwd: String?,
    val apiVersion: Int
)