/*
 * 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 <stdlib.h>
#include <string.h>
#include "util_resource_private.h"
#include "util/util.h"
#include "protocol/protocol_request.h"
#include "iotcs_port_crypto.h"

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

struct get_next_string_ctx {
    const iotcs_resource_message_base* resources;
    int len;
    int pos;
};

static const char* get_next_string(void *data) {
    struct get_next_string_ctx *p = (struct get_next_string_ctx*) data;
    if (p->pos == p->len) {
        return NULL;
    }
    return p->resources[p->pos++].path;
}

iotcs_result util_resources_get_md5(char *output_buffer, const iotcs_resource_message_base* resources, int resources_len) {
    struct get_next_string_ctx ctx = {resources, resources_len, 0};
    iotcs_result rv;
    if (IOTCS_RESULT_OK != (rv = iotcs_port_md5((unsigned char*)output_buffer + IOTCS_MD5_DIGEST_LENGTH, get_next_string, (void*)&ctx))) {
        return rv;
    }
    
    util_digest_to_hex(output_buffer, (unsigned char*)output_buffer + IOTCS_MD5_DIGEST_LENGTH, IOTCS_MD5_DIGEST_LENGTH);
    
    return IOTCS_RESULT_OK;
}
