/*
 * record.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 <string.h>

#include "record.h"

#define DEBUG 10
#include "debug.h"

GtkListStore *record_store = NULL;
static int record_enabled = 0;

int record_init(void)
{
	record_store = gtk_list_store_new(RECORD_COL_MAX,
			G_TYPE_INT, G_TYPE_STRING,
			G_TYPE_STRING, G_TYPE_INT,
			G_TYPE_INT, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING);
	

	return 1;
}


void record_enable(int enable)
{
	record_enabled = enable;
}

void record_cleanup(void)
{
	g_object_unref(record_store);
	record_store = NULL;
}


void record_append(int time, const char *cmd, const char *address, int remote, int state, const char *state_param, int is_valid, const char *desc)
{
	GtkTreeIter iter;

	if(!record_enabled)
		return;
	
	gtk_list_store_append(record_store, &iter);
	gtk_list_store_set(record_store, &iter,
			RECORD_COL_TIME, time,
			RECORD_COL_CMD, cmd,
			RECORD_COL_ADDRESS, address,
			RECORD_COL_REMOTE, remote,
			RECORD_COL_STATE, state,
			RECORD_COL_STATE_PARAM, state_param,
			RECORD_COL_IS_VALID, is_valid,
			RECORD_COL_DESC, desc,
			-1);
}


int record_get_last_state(const char *addr)
{
	/* TODO
	 * 	- do this better
	 */
	
	GtkTreeIter iter;
	int valid, ret = 0;

	if(!record_enabled)
		return -1;
	
	valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(record_store), &iter);
	while (valid) {
		char *a, *cmd;
		int st;
		
		gtk_tree_model_get(GTK_TREE_MODEL(record_store), &iter, RECORD_COL_ADDRESS, &a, RECORD_COL_CMD, &cmd, RECORD_COL_STATE, &st, -1);
		
		if (strcmp(addr, a) == 0 && (cmd[0] == 'i' || cmd[0] == 'c')) {
			ret = st;
		}
		
		valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(record_store), &iter);
	}
	return ret;
}


