#include "system_state.h"

#include <zephyr/kernel.h>

#define STATE_EVENT_NETWORK BIT(0)
#define STATE_EVENT_MQTT    BIT(1)

K_EVENT_DEFINE(state_events);

static int wait_for_state(uint32_t mask, k_timeout_t timeout)
{
	uint32_t events = k_event_wait(&state_events, mask, false, timeout);

	return (events & mask) ? 0 : -ETIMEDOUT;
}

void system_state_set_network_ready(bool ready)
{
	if (ready) {
		k_event_post(&state_events, STATE_EVENT_NETWORK);
	} else {
		k_event_clear(&state_events, STATE_EVENT_NETWORK);
	}
}

void system_state_set_mqtt_ready(bool ready)
{
	if (ready) {
		k_event_post(&state_events, STATE_EVENT_MQTT);
	} else {
		k_event_clear(&state_events, STATE_EVENT_MQTT);
	}
}

int system_state_wait_for_network(k_timeout_t timeout)
{
	return wait_for_state(STATE_EVENT_NETWORK, timeout);
}

int system_state_wait_for_mqtt(k_timeout_t timeout)
{
	return wait_for_state(STATE_EVENT_MQTT, timeout);
}
