package club.clubk.ktag.apps.sharedservices

import android.content.Context
import androidx.preference.PreferenceManager
import java.util.UUID

/**
 * Data class holding MQTT connection configuration loaded from SharedPreferences.
 */
data class MqttConnectionConfig(
    val deviceId: String,
    val serverUri: String,
    val username: String,
    val password: String,
    val battlefield: String,
    val autodiscovery: Boolean
) {
    companion object {
        /**
         * Load MQTT configuration from the app's default SharedPreferences.
         */
        @JvmStatic
        fun fromPreferences(context: Context): MqttConnectionConfig {
            val prefs = PreferenceManager.getDefaultSharedPreferences(context)
            return MqttConnectionConfig(
                deviceId = prefs.getString(MqttPreferenceKeys.DEVICE_ID, null)
                    ?.takeIf { it.isNotBlank() }
                    ?: UUID.randomUUID().toString().also {
                        prefs.edit().putString(MqttPreferenceKeys.DEVICE_ID, it).apply()
                    },
                serverUri = prefs.getString(
                    MqttPreferenceKeys.SERVER_URI,
                    MqttPreferenceKeys.DEFAULT_SERVER_URI
                ) ?: MqttPreferenceKeys.DEFAULT_SERVER_URI,
                username = prefs.getString(MqttPreferenceKeys.USERNAME, "") ?: "",
                password = prefs.getString(MqttPreferenceKeys.PASSWORD, "") ?: "",
                battlefield = prefs.getString(
                    MqttPreferenceKeys.BATTLEFIELD,
                    MqttPreferenceKeys.DEFAULT_BATTLEFIELD
                ) ?: MqttPreferenceKeys.DEFAULT_BATTLEFIELD,
                autodiscovery = prefs.getBoolean(MqttPreferenceKeys.AUTODISCOVERY, true)
            )
        }
    }
}
