package club.clubk.ktag.apps.mqttbroker

import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.Build
import android.text.format.Formatter
import androidx.preference.PreferenceManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

sealed class BrokerStatus {
    data object Stopped : BrokerStatus()
    data object Starting : BrokerStatus()
    data class Running(val port: Int, val sslPort: Int? = null) : BrokerStatus()
    data class Error(val message: String) : BrokerStatus()
}

object MqttBrokerManager {

    private val _status = MutableStateFlow<BrokerStatus>(BrokerStatus.Stopped)
    val status: StateFlow<BrokerStatus> = _status.asStateFlow()

    @JvmStatic
    fun updateStatus(status: BrokerStatus) {
        _status.value = status
    }

    fun isBrokerEnabled(context: Context): Boolean {
        val prefs = PreferenceManager.getDefaultSharedPreferences(context)
        return prefs.getBoolean(BrokerPreferenceKeys.BROKER_ENABLED, false)
    }

    fun startBroker(context: Context) {
        val intent = Intent(context, MqttBrokerService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent)
        } else {
            context.startService(intent)
        }
    }

    fun stopBroker(context: Context) {
        val intent = Intent(context, MqttBrokerService::class.java)
        context.stopService(intent)
    }

    fun startBrokerIfEnabled(context: Context) {
        if (isBrokerEnabled(context)) {
            startBroker(context)
        }
    }

    @Suppress("DEPRECATION")
    fun getDeviceIpAddress(context: Context): String? {
        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
            ?: return null
        val ipInt = wifiManager.connectionInfo.ipAddress
        if (ipInt == 0) return null
        return Formatter.formatIpAddress(ipInt)
    }
}
