#pragma once

void sendToApp(String jsonMessage) {
	if (activeClient && activeClient->status() == WS_CONNECTED) {
	    activeClient->text(jsonMessage);
	  } else {
	    Serial.println("No active WebSocket client connected.");
	  }
}

void replyOnWebSocket(AsyncWebSocketClient *client, String list) {
    LOG_DEBUG("Sending WebSocket reply: %s", list.c_str());
    client->text(list);
}

// Handles incoming WebSocket messages on subscribed topics.
// Could move logic out of this into a dedicated function.
void onWebSocketReceived(AsyncWebSocketClient *client, void *arg, uint8_t *data, size_t len) {
    AwsFrameInfo *info = (AwsFrameInfo*)arg;
    if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
        data[len] = '\0'; // Null-terminate the received data
        Serial.printf("Received message: %s\n", (char*)data);

				JsonDocument json = payload2json((char*)data);
				handleCommand(json, client);
    }
}


void onWebSocketEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
    if (type == WS_EVT_DATA) {
        onWebSocketReceived(client, arg, data, len);
				Serial.println("WebSocket Message Received");
    }
		if (type == WS_EVT_CONNECT) {
			Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
			activeClient = client;  // Save the connected client
		}
		if (type == WS_EVT_DISCONNECT) {
			Serial.printf("WebSocket client #%u disconnected\n", client->id());
			if (client == activeClient) {
				activeClient = nullptr; // Clear it if it's the one we saved
			}
		}
		if (type == WS_EVT_ERROR) {
			Serial.printf("WebSocket client #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
		}

}
