/*
 * 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"

// see iotcs_message_severity
static const char* CL_SEVERITY_LEVEL_STRING[] = {
    "CRITICAL", // 0 
    "SIGNIFICANT", // 1
    "NORMAL", // 2
    "LOW" // 3
};

static int alert_message_callback(json_buf *buf, int pos, void *data) {
    int rv;
    int original_pos = pos;
    const iotcs_alert_message* alert_msg = (const iotcs_alert_message *) data;
    const iotcs_data_item_desc* item;
    iotcs_value* value;

    item = alert_msg->items_desc;
    GOTO_ERR(!item);

    value = alert_msg->items_value;

    while (item->key) {
        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++;
    };

    if(pos > original_pos) --pos; /* remove last comma if something is written */

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

int msg_alert_toJSON(json_buf *buf, int pos, void* data) {
    int rv;
    int original_pos = pos;
    iotcs_message* message = (iotcs_message*) data;
    const iotcs_alert_message* alert_msg = NULL;

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

    alert_msg = &message->u.alert;

    rv = json_write_string_field(buf, pos, "format", alert_msg->base->format);
    JSON_MOVE_POS(pos, rv);
    JSON_PUT_SYMBOL(buf, pos, ',');

    rv = json_write_string_field(buf, pos, "description", alert_msg->base->description);
    JSON_MOVE_POS(pos, rv);
    JSON_PUT_SYMBOL(buf, pos, ',');

    rv = json_write_string_field(buf, pos, "severity", CL_SEVERITY_LEVEL_STRING[alert_msg->base->severity_level]);
    JSON_MOVE_POS(pos, rv);
    JSON_PUT_SYMBOL(buf, pos, ',');


    rv = json_write_object_field(buf, pos, "data", alert_message_callback, (void*) alert_msg);
    JSON_MOVE_POS(pos, rv);

    return pos - original_pos;

error:
    return -1;
}
