/*
 * serviceid.c
 *
 * Copyright (C) Leni Mayo 2001-2002
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License, version 2, as
 *	published by the Free Software Foundation.
 *	
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *	
 *	You should have received a copy of the GNU General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdlib.h> /* for malloc and free */
#include <string.h> /* for strcpy */
#include <glib.h>
#include "log.h"
#include "serviceid.h"

static GHashTable *pTable = NULL;

static void asStringCallback(gpointer key, gpointer value, gpointer pUserData);

/*
 * serviceIdInitialise()
 *
 * Returns
 *   TRUE if it initialised ok, FALSE otherwise
 */
int serviceIdInitialise()
{
	pTable = g_hash_table_new(g_str_hash, g_str_equal);

	assert(sizeof(char *) <= sizeof(gpointer));

	return (pTable != NULL);
}

void serviceIdCleanup()
{
	if (pTable != NULL)
	{
		g_hash_table_foreach(pTable, callbackFreeValue, NULL);

		g_hash_table_destroy(pTable);
	}
}

ServiceId serviceIdAdd(const ServiceName name)
{
	gpointer pszValue;

	assert(pTable);
	assert(serviceIdFromName(name) == NULL);

	pszValue = malloc(sizeof(ServiceName));
	assert(pszValue != NULL); /* leni TODO: better response to out of memory */

	strcpy(pszValue, name);

	g_hash_table_insert(pTable, pszValue, pszValue);

	return pszValue;
}

ServiceId serviceIdFromName(const ServiceName name)
{
	gpointer value;

	assert(pTable);

	value = g_hash_table_lookup(pTable, (gpointer) name);

	return value;
}

void serviceIdRemove(const ServiceId id)
{
	gpointer value;

	assert(pTable);

	value = g_hash_table_lookup(pTable, id);

	assert(value != NULL);

	g_hash_table_remove(pTable, id);

	free(value);
}

const char * serviceIdAsString(const ServiceId id)
{
	return (const char *) id;
}

const char * serviceIdsAsString(char *buf, int bufsiz)
{
	SafeBuf x;

	x.buf    = buf;
	x.bufsiz = bufsiz;

	g_hash_table_foreach(pTable, asStringCallback, &x);
	
	return buf;
}

void asStringCallback(gpointer key, gpointer value, gpointer pUserData)
{
	const char *psz = (const char *) value;
	SafeBuf *pX = (SafeBuf *) pUserData;

	sprintfTo(pX, "    %p : %s\n", key, psz);
}
