/*
 * roles.c
 * 
 * Copyright (C) 2007  Josef Kufner <jk@myserver.cz>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "roles.h"

#define DEBUG 0
#include "debug.h"


GtkListStore *roles_store = NULL;
static int roles_store_nextid = 0;


int roles_init(void)
{
	DBG_MSG(1, "");
	assert(roles_store == NULL);

	roles_store = gtk_list_store_new(ROLE_COL_MAX, G_TYPE_STRING, G_TYPE_INT);
	roles_clear();
	return 1;
}


int roles_clear(void)
{
	assert(roles_store != NULL);
	
	DBG_MSG(1, "");
	gtk_list_store_clear(roles_store);
	roles_store_nextid = 0;

	return 1;
}


int roles_add(const gchar *role)
{
	GtkTreeIter iter;
	assert(roles_store != NULL);
	
	DBG_MSG(1, "%s", role);
	
	gtk_list_store_append(roles_store, &iter);
	gtk_list_store_set(roles_store, &iter, ROLE_COL_NAME, role, ROLE_COL_ID, roles_store_nextid++, -1);

	return 1;
}


/*
 * Searches role in role_store.
 * Returns it's index or -1 if none found.
 */
int roles_get_id_by_name(const char *role)
{
	GtkTreeIter iter;
	int valid, i = 0;

	assert(roles_store != NULL);

	DBG_MSG(2, "%s", role);

	valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(roles_store), &iter);
	while (valid) {
		gchar *r;
		int comp;
		
		gtk_tree_model_get(GTK_TREE_MODEL(roles_store), &iter, ROLE_COL_NAME, &r, -1);
		comp = strcmp(role, r);
		g_free(r);

		if (comp == 0) {
			return i;
		}

		i++;
		valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(roles_store), &iter);
	}
	return -1;
}


int roles_get_by_iter(GtkTreeIter *iter, gchar **role, gint *role_id)
{
	assert(iter != NULL);
	assert(role != NULL);
	assert(role_id != NULL);

	*role = NULL;
	gtk_tree_model_get(GTK_TREE_MODEL(roles_store), iter,
			ROLE_COL_NAME, role, ROLE_COL_ID, role_id, -1);

	return role != NULL;
}


