/*
 * 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 "util/util_key_value.h"
#include "util.h"
#include <string.h>
#include "util/util_memory.h"

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

iotcs_key_value* util_key_value_new(const char* key, const char* value) {
    iotcs_key_value* new_field = NULL;
    char* key_copy = NULL;
    char* value_copy = NULL;
    GOTO_ERR(!key || !value);
    new_field = (iotcs_key_value*) util_malloc(sizeof (iotcs_key_value));
    GOTO_ERR_CRIT(!new_field);
    key_copy = util_safe_strcpy(key);
    GOTO_ERR_CRIT(!key_copy);
    value_copy = util_safe_strcpy(value);
    GOTO_ERR_CRIT(!value_copy);
    new_field->key = key_copy;
    new_field->value = value_copy;
    return new_field;

error:
    util_free(key_copy);
    util_free(value_copy);
    util_free(new_field);
    return NULL;
}

int util_compare_by_key(iotcs_key_value* field1, iotcs_key_value* field2) {
    if (!field1 || !field2) {
        return -1;
    }
    return strcmp(field1->key, field2->key);
}

int util_compare_by_value(iotcs_key_value* field1, iotcs_key_value* field2) {
    if (!field1 || !field2) {
        return -1;
    }
    return strcmp(field1->value, field2->value);
}

void util_key_value_free(void* entry) {
    iotcs_key_value* entry_t = (iotcs_key_value*) entry;
    if (!entry_t) return;
    util_free((char*) entry_t->key);
    util_free((char*) entry_t->value);
    util_free(entry_t);
}
