/*
 * LEIGH:plc
 * Copyright 2022 Alex Leigh
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <esp_log.h>
#include <cJSON.h>

#include "tlm.h"

/**
 * @brief Allocate a telemetry frame.
 * 
 * Allocates a new telemetry frame. The time in the frame is left blank under the
 * belief that the ESP32 does not have a realtime clock and therefore does not
 * actually reliably know the time.
 * 
 * The symbols array is pre-populated.
 * 
 * @return cJSON* 
 */
cJSON *tlmFframe_alloc() {
    cJSON *frame = cJSON_CreateObject();

    cJSON_AddArrayToObject(frame, TLM_KEY_SYMBOLS);

    return frame;
}

/**
 * @brief Allocate a new telemetry symbol.
 * 
 * @param name 
 * @return cJSON* 
 */
cJSON* tlmFframe_symbol_alloc(const char *name, const char *value, const char *uom) {
    cJSON *sym = cJSON_CreateObject();
    cJSON_AddStringToObject(sym, TLM_KEY_NAME, name);
    cJSON_AddStringToObject(sym, TLM_KEY_VALUE, value);
    cJSON_AddStringToObject(sym, TLM_KEY_UOM, uom);
    cJSON_AddBoolToObject(sym, TLM_KEY_PRIMARY, cJSON_True);
    cJSON_AddBoolToObject(sym, TLM_KEY_LOS, cJSON_False);
    
    return sym;
}

/**
 * @brief Get the symbols array
 * 
 * Given a telemetry frame, return the symbols array.
 * 
 * @param frame 
 * @return cJSON* 
 */
cJSON *tlmFframe_get_symbols(cJSON *frame) {
    return cJSON_GetObjectItem(frame, TLM_KEY_SYMBOLS);
}