package com.example.uitugasakhir.ViewModel

import android.app.Application
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import com.example.uitugasakhir.mqtt.MqttManager
import org.json.JSONObject

data class MQTTState(
    val pump: String = "OFF",
    val mode: String = "Manual",
    val alarm: String = "AMAN"
)

class MQTTViewModel(
    application: Application
) : AndroidViewModel(application) {

    private val mqtt = MqttManager(application)

    var state by mutableStateOf(MQTTState())
        private set

    init {

        mqtt.connect(

            onMessage = { topic, message ->

                Log.d("MQTT_TOPIC", topic)
                Log.d("MQTT_MESSAGE", message)

                when (topic) {

                    // =========================
                    // PUMP REALTIME
                    // =========================
                    "smartplant/pump" -> {

                        state = state.copy(
                            pump = message
                        )
                    }

                    // =========================
                    // ALARM REALTIME
                    // =========================
                    "smartplant/alarm" -> {

                        state = state.copy(
                            alarm = message
                        )
                    }

                    // =========================
                    // MODE REALTIME
                    // =========================
                    "smartplant/mode" -> {

                        state = state.copy(
                            mode = message
                        )
                    }
                }
            }
        )
    }

    // =========================
    // CONTROL PUMP
    // =========================
    fun setPump(status: Boolean) {

        val msg = if (status) "ON" else "OFF"

        mqtt.publish(
            "smartplant/manualPump",
            msg
        )

        state = state.copy(
            pump = msg
        )
    }

    // =========================
    // CONTROL MODE
    // =========================
    fun setMode(mode: String) {

        mqtt.publish(
            "smartplant/mode",
            mode
        )

        state = state.copy(
            mode = mode
        )
    }
}