#include "WebServer.hpp"
#include "../KnxWorker.hpp"
#include "../Gui.hpp"
#include <cstring>

esp_err_t WebServer::getKnxAddressesHandler(httpd_req_t* req) {
    KnxWorker& knxWorker = Gui::knxWorker;
    size_t count = knxWorker.getGroupObjectCount();

    cJSON* arr = cJSON_CreateArray();

    for (size_t i = 1; i <= count; i++) {
        KnxGroupObjectInfo info;
        if (knxWorker.getGroupObjectInfo(i, info)) {
            char addrStr[16];
            KnxWorker::formatGroupAddress(info.groupAddress, addrStr, sizeof(addrStr));

            cJSON* obj = cJSON_CreateObject();
            cJSON_AddNumberToObject(obj, "index", info.goIndex);
            cJSON_AddNumberToObject(obj, "addr", info.groupAddress);
            cJSON_AddStringToObject(obj, "addrStr", addrStr);
            cJSON_AddBoolToObject(obj, "comm", info.commFlag);
            cJSON_AddBoolToObject(obj, "read", info.readFlag);
            cJSON_AddBoolToObject(obj, "write", info.writeFlag);
            cJSON_AddItemToArray(arr, obj);
        }
    }

    char* str = cJSON_PrintUnformatted(arr);
    httpd_resp_set_type(req, "application/json");
    httpd_resp_send(req, str, strlen(str));
    free(str);
    cJSON_Delete(arr);
    return ESP_OK;
}
