/*  gnutrition - a nutrition and diet analysis program.
 *  Copyright(C) 2000, 2001 Edgar Denny(e.denny@ic.ac.uk)
 *
 *  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.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <gnome.h>
#include <glade/glade.h>

#include "text_util.h"
#include "food.h"
#include "recipe.h"
#include "nutr_goal.h"
#include "nutr_goal_dlg_ui.h"
#include "init_database.h"
#include "wrap_mysql.h"

/* get the nutrient goal from the database. */
GList *
gnutr_get_nutrition_goal()
{
	GList *list;
	char *person_name, *person_no;
	char *query;

	person_name = get_person_name();
	g_assert( person_name);

	query = g_strconcat( "SELECT person_no FROM person WHERE ",
		"person_name = '", person_name, "'", NULL);
	person_no = single_ret_val_query_db( query);
	g_assert( person_no);
	g_free( query);

	query = g_strconcat( "SELECT nutr_no, goal_val FROM nutr_goal WHERE ",
		"person_no = '", person_no, "'", NULL);
	list = rows_glist_ret_val_query_db( query);
	g_assert( list);
	g_free( query);
	g_free( person_no);

	return list;
}

/* save the nutient goal to the database. */
void
gnutr_save_nutr_goal( GList *list)
{
	char *person_name, *person_no;
	char *query;
	GList *ptr;
	char **elm;
	gboolean success;

	g_return_if_fail( list);

	person_name = get_person_name();
	g_assert( person_name);

	query = g_strconcat( "SELECT person_no FROM person WHERE ",
		"person_name = '", person_name, "'", NULL);
	person_no = single_ret_val_query_db( query);
	g_assert( person_no);
	g_free( query);

	/* delete the old nutrient goals, if there are any. */
	query = g_strconcat( "DELETE FROM nutr_goal WHERE ",
		"person_no = '", person_no, "'", NULL);
	success = no_ret_val_query_db( query);
	g_assert( success);
	g_free( query);
	g_free( person_no);

	/* insert new nutrient goals. */
	for ( ptr = list; ptr; ptr = ptr->next) {
		elm = (char **)ptr->data;
		/* elm[0] = nutr_no, elm[1] = goal_val. */

		query = g_strconcat( "INSERT INTO nutr_goal VALUES ",
			"('", person_no, "', '", elm[0], "', '", 
			elm[1], "')", NULL);
		success = no_ret_val_query_db( query);
		g_assert( success);
	}
	gnutr_free_row_list( list, 2);
}
