/*
 * 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 <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "iotcs.h"
#include "protocol/protocol_request.h"
#include "json/json_helper.h"
#include "util/util.h"
#include "util/util_key_value.h"
#include "iotcs/iotcs_private.h"

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

/**< Array of the possible names of the http methods. */
const char* PROTOCOL_REQUEST_METHOD_STRING[] = {
    "DELETE", "GET", "HEAD", "POST", "PUT"
};

static int iotcs_strnicmp(const char *s1, const char *s2, int len) {
    int i = 0;
    while (i < len) {
        if (tolower((int) s1[i]) != tolower((int) s2[i])) {
            return 1;
        }
        i++;
    }
    return 0;
}

iotcs_result protocol_string_to_request_method(const char *str, int str_len, iotcs_request_method *pmethod) {
    int i;

    for (i = 0; i < (int)ARRAY_SIZE(PROTOCOL_REQUEST_METHOD_STRING); ++i) {
        if (iotcs_strnicmp(str, PROTOCOL_REQUEST_METHOD_STRING[i], str_len) == 0) {
            *pmethod = (iotcs_request_method) 1 << i;
            return IOTCS_RESULT_OK;
        }
    }

    return IOTCS_RESULT_FAIL;
}

const char* protocol_request_methods_to_string(PROTOCOL_REQUEST_METHOD methods) {
    if (methods & PROTOCOL_REQUEST_METHOD_DELETE) {
        return PROTOCOL_REQUEST_METHOD_STRING[0];
    }
    if (methods & PROTOCOL_REQUEST_METHOD_GET) {
        return PROTOCOL_REQUEST_METHOD_STRING[1];
    }
    if (methods & PROTOCOL_REQUEST_METHOD_HEAD) {
        return PROTOCOL_REQUEST_METHOD_STRING[2];
    }
    if (methods & PROTOCOL_REQUEST_METHOD_POST) {
        return PROTOCOL_REQUEST_METHOD_STRING[3];
    }
    if (methods & PROTOCOL_REQUEST_METHOD_PUT) {
        return PROTOCOL_REQUEST_METHOD_STRING[4];
    }
    return NULL;
}
