/*
 * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 *
 * This software is dual-licensed to you under the MIT License (MIT) and
 * the Universal Permissive License (UPL). See the LICENSE file in the root
 * directory for license terms. You may choose either license, or both.
 */

#include "json/json_helper.h"
#include "msg_private.h"
#include "util/util_memory.h"
#include "util/util.h"

#include "log/log.h"
#define IOTCSP_MODULE_LOG_CHANNEL LOG_CHANNEL_MSG
#include "log/log_template.h"

static int data_message_callback(json_buf *buf, int pos, void *data) {
    int rv;
    int original_pos = pos;
    const iotcs_data_message* data_msg = (const iotcs_data_message *) data;
    const iotcs_data_item_desc* item;
    iotcs_value* value;

    item = data_msg->items_desc;
    GOTO_ERR(!item || !item->key);

    value = data_msg->items_value;
    GOTO_ERR(!value);

    do {
        GOTO_ERR(strcmp(item->key, "") == 0);
        rv = json_write_iotcs_value_field(buf, pos, item->key, *value, item->type);
        JSON_MOVE_POS(pos, rv);
        JSON_PUT_SYMBOL(buf, pos, ',');
        item++;
        value++;
    } while (item->key);

    --pos; /* remove last comma */

    return pos - original_pos;
error:
    return -1;
}

int msg_data_toJSON(json_buf *buf, int pos, void *data) {
    int rv;
    int original_pos = pos;
    iotcs_message* message = (iotcs_message*) data;
    const iotcs_data_message* data_msg = NULL;

    if (!message || message->base->type != IOTCS_MESSAGE_DATA ||
            !message->u.data.base || !message->u.data.base->format ||
            strcmp(message->u.data.base->format, "") == 0) {
        return -1;
    }

    data_msg = &message->u.data;
    rv = json_write_string_field(buf, pos, "format", data_msg->base->format);
    JSON_MOVE_POS(pos, rv);
    JSON_PUT_SYMBOL(buf, pos, ',');

    rv = json_write_object_field(buf, pos, "data", data_message_callback, (void*) data_msg);
    JSON_MOVE_POS(pos, rv);

    return pos - original_pos;

error:
    return -1;
}