/*
 * 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 <string.h>
#include "msg_private.h"
#include "util/util.h"
#include "util/util_key_value.h"
#include "json/json_helper.h"
#include "iotcs_port_crypto.h"

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

int msg_response_toJSON(json_buf *buf, int pos, void* data) {
    size_t rv;
    int original_pos = pos;
    iotcs_message* message = (iotcs_message*) data;
    const iotcs_response_message* resp_msg;

    if (!message || message->base->type != IOTCS_MESSAGE_RESPONSE || message->u.response.request == NULL) {
        return -IOTCS_RESULT_INVALID_ARGUMENT;
    }

    resp_msg = &message->u.response;

    rv = json_write_int_field(buf, pos, "statusCode", resp_msg->status_code);
    JSON_MOVE_POS(pos, rv);
    JSON_PUT_SYMBOL(buf, pos, ',');

    rv = json_write_string_field(buf, pos, "url", resp_msg->request->url);
    JSON_MOVE_POS(pos, rv);
    JSON_PUT_SYMBOL(buf, pos, ',');

    rv = json_write_string_field(buf, pos, "requestId", resp_msg->request->id);
    JSON_MOVE_POS(pos, rv);
    JSON_PUT_SYMBOL(buf, pos, ',');

    /* TODO: add headers to JSON */
    rv = json_write_object_field(buf, pos, "headers", json_noop_callback, NULL);
    JSON_MOVE_POS(pos, rv);
    JSON_PUT_SYMBOL(buf, pos, ',');

    rv = json_write_string(buf, pos, "body");
    JSON_MOVE_POS(pos, rv);
    JSON_PUT_SYMBOL(buf, pos, ':');
    JSON_PUT_SYMBOL(buf, pos, '"');
    if (resp_msg->body) {
        rv = buf->len - pos;
        GOTO_ERR(iotcs_port_crypto_encode_base64(buf->buf + pos, &rv, resp_msg->body, strlen(resp_msg->body)) != IOTCS_RESULT_OK);
        JSON_MOVE_POS(pos, rv);
    }
    JSON_PUT_SYMBOL(buf, pos, '"');

    return pos - original_pos;

error:
    return -IOTCS_RESULT_OUT_OF_MEMORY;
}
