/*
 * OpenMRCP - Open Source Media Resource Control Protocol Stack
 * Copyright (C) 2007, Cepstral LLC
 *
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Author(s):
 * Arsen Chaloyan <achaloyan@yahoo.com>
 *
 * Contributor(s):
 *
 */

#include <ctype.h>
#include "apt_string_table.h"

/* Get the string associated with a given id from the table */
APT_DECLARE(const char*) apt_string_table_get(const apt_string_table_item_t *table, apr_size_t size, apr_size_t id)
{
	if(id >= size) {
		return NULL;
	}
	return table[id].value;
}

/* Find the id associated with a given string from the table */
APT_DECLARE(apr_size_t) apt_string_table_find(const apt_string_table_item_t *table, apr_size_t size, const char *value)
{
	/* Key character is stored within each apt_string_table_item.
	At first, key characters must be matched in a loop crossing the items.
	Then only for the matched item whole strings should be compared.
	Key characters should be automatically generated once for a given string table. */

	apr_size_t i;
	apr_size_t length = strlen(value);
	for(i=0; i<size; i++) {
		/* check whether key is available */
		if(table[i].key < length) {
		    /* check whether values are matched by key (using no case compare) */
			if(length == table[i].length && 
				tolower(table[i].value[table[i].key]) == tolower(value[table[i].key])) {
				/* whole strings must be compared to ensure, should be done only once for any lookup */
				if(apt_str_compare(table[i].value,value) == TRUE) {
					return i;
				}
			}
		}
		else {
			/* no key available, just do generic comparison */
			if(apt_str_compare(table[i].value,value) == TRUE) {
				return i;
			}
		}
	}

	return size;
}
