package vassistent.model;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * Observable in-memory state shared between services and UI controllers.
 */
public class AppState {

    private long dataVersion = 0;
    private boolean mqttConnected;
    private ProblemLevel problemLevel = ProblemLevel.NONE;

    private final List<Consumer<AppState>> listeners =
            new ArrayList<>();

    /**
     * Registers a state listener that is notified on relevant updates.
     *
     * @param listener callback receiving the current state instance
     */
    public void addListener(Consumer<AppState> listener) {
        listeners.add(listener);
    }

    /**
     * Notifies all currently registered listeners.
     */
    private void notifyListeners() {
        new ArrayList<>(listeners).forEach(l -> l.accept(this));
    }

    /**
     * Returns the current computed problem level.
     *
     * @return current problem level
     */
    public ProblemLevel getProblemLevel() {
        return problemLevel;
    }

    /**
     * Updates the problem level and notifies listeners.
     *
     * @param problemLevel new problem level
     */
    public void setProblemLevel(ProblemLevel problemLevel) {
        this.problemLevel = problemLevel;
        dataVersion++;
        notifyListeners();
    }

    /**
     * Indicates whether MQTT is currently connected.
     *
     * @return {@code true} if connected, otherwise {@code false}
     */
    public boolean isMqttConnected() {
        return mqttConnected;
    }

    /**
     * Updates MQTT connection status and notifies listeners only when changed.
     *
     * @param mqttConnected new MQTT connection flag
     */
    public void setMqttConnected(boolean mqttConnected) {
        if (this.mqttConnected != mqttConnected) {
            this.mqttConnected = mqttConnected;
            notifyListeners();
        }
    }
}
