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

#if defined( LIBXML_VERSION) && LIBXML_VERSION >= 20000
        #include <xmlmemory.h>
        #include <libxml/parser.h>
        #include <libxml/tree.h>
        #define root children
        #define childs children
#else
        #include <gnome-xml/parser.h>
        #include <gnome-xml/tree.h>
        #include <gnome-xml/xmlmemory.h>
#endif

#include "text_util.h"
#include "food.h"
#include "plan.h"
#include "plan_win.h"
#include "wrap_mysql.h"
#include "init_database.h"
#include "person.h"

/* get the real name of the person from the database. */
char *
get_name_from_db( char *user)
{
	char *query;
	char *person_name;

	query = g_strconcat( "SELECT person_name FROM person ",
		"WHERE user_name = '", user, "'", NULL);
	person_name = single_ret_val_query_db( query);
	g_assert( person_name);
	return person_name;	
}

void
add_name_to_person_table( char *person_name)
{
	char *query;
	char *user;
	GList *list, *ptr;
	gboolean success;

	user = gnutr_get_connected_user();

	/* This function is called during the druid setup. There should
	 * always be and entry in the person table during a normal
	 * session. */
	query = g_strdup( "SELECT person_name FROM person");
	list = get_glist_fields_query_db( query);
	g_free( query);

	if ( !list) { 
		char *person_no;

		/* there are no persons in the table, 
		this is the first row to be put in the table. */
		person_no = g_strdup( "100001");

		query = g_strconcat( "INSERT INTO person VALUES ",
			"( '", person_no, "', '", person_name, 
			"', '", user, "')", NULL);
		success = no_ret_val_query_db( query);
		g_free( query);
		g_free( person_no);
		g_assert( success);
	} else {
		gboolean name_match = FALSE;
		char *name;

		/* check that the person_name isn't already in table. */
		for ( ptr = list; ptr; ptr = ptr->next) {
			name = (char *)ptr->data;
			if ( strcmp( name, person_name) == 0) {
				name_match = TRUE;
				break;
			}
		}

		if ( !name_match) {
			query = g_strconcat( "INSERT INTO person VALUES ",
				"( NULL, '", person_name, 
				"', '", user, "')", NULL);
			success = no_ret_val_query_db( query);
			g_free( query);
			g_assert( success);
		}
		gnutr_free_field_list( list);
	}
	g_free( user);
}

/* create a series of temporary tables that a user need each time
 * they use the application */
void
gnutr_user_initialize()
{
	char *query;
	gboolean success;
	GList *list = NULL, *ptr;
	char **elm;
	char *person_no;

	person_no = gnutr_get_connected_person_no();

	/* drop temporary tables if they exist. */
	query = g_strdup( "DROP TABLE IF EXISTS food_plan_temp");
	success =  no_ret_val_query_db( query);
	g_assert( success);
	g_free( query);

	query = g_strdup( "DROP TABLE IF EXISTS recipe_plan_temp");
	success =  no_ret_val_query_db( query);
	g_assert( success);
	g_free( query);

	/* create the temporary tables to store the plan. */
	query = g_strconcat( "CREATE TEMPORARY TABLE food_plan_temp ",
		"( person_no SMALLINT(6) UNSIGNED NOT NULL, ",
		"date DATE NOT NULL, ",
		"time TIME NOT NULL, ",
		"amount FLOAT(7,2), ",
		"msre_no MEDIUMINT(5) UNSIGNED NOT NULL, ",
		"fd_no SMALLINT(5) UNSIGNED NOT NULL, ",
		"INDEX (date, time, fd_no) )", NULL);
	success = no_ret_val_query_db( query);
	g_assert( success);
	g_free( query);

	query = g_strconcat( "CREATE TEMPORARY TABLE recipe_plan_temp ",
		"( person_no SMALLINT(6) UNSIGNED NOT NULL, ",
		"date DATE NOT NULL, ",
		"time TIME NOT NULL, ",
		"no_portions FLOAT(7,2) NOT NULL, ",
		"recipe_no MEDIUMINT(6) UNSIGNED NOT NULL, ", 
		"INDEX (date, recipe_no, time) )", NULL);
	success = no_ret_val_query_db( query);
	g_assert( success);
	g_free( query);

	/* put any existing data from the stored tables into the
	 * temporary_tables. */
	query = g_strconcat( "SELECT * FROM food_plan WHERE ",
		"person_no = '", person_no, "'", NULL);
	list = rows_glist_ret_val_query_db( query);
	g_free( query);

	for ( ptr = list; ptr; ptr = ptr->next) {
		elm = ( char **)ptr->data;

		query = g_strconcat( "INSERT INTO food_plan_temp "
			"VALUES ( '", elm[0], "', '", elm[1], "', '", elm[2], 
			"', '", elm[3], "', '", elm[4], "', '", elm[5], "' )", 
			NULL);
		success = no_ret_val_query_db( query);
		g_assert( success);
		g_free( query);
	}
	if ( list) gnutr_free_row_list( list, 6);

	query = g_strconcat( "SELECT * FROM recipe_plan WHERE ",
		"person_no = '", person_no, "'", NULL);
	list = rows_glist_ret_val_query_db( query);
	g_free( query);

	for ( ptr = list; ptr; ptr = ptr->next) {
		elm = ( char **)ptr->data;

		query = g_strconcat( "INSERT INTO recipe_plan_temp "
			"VALUES ( '", elm[0], "', '", elm[1], "', '", elm[2], 
			"', '", elm[3], "', '", elm[4], "' )", NULL);
		success = no_ret_val_query_db( query);
		g_assert( success);
		g_free( query);
	}
	if ( list) gnutr_free_row_list( list, 5);
}

char *
gnutr_get_connected_user()
{
	char *query;
	char *name = NULL;

	query = g_strdup( "SELECT SUBSTRING_INDEX( USER(), \"@\", 1)");

	name = single_ret_val_query_db( query);
	g_assert( name);

	g_free( query);
	return name;
}

char *
gnutr_get_connected_person_no()
{
	char *query;
	char *user_name;
	char *person_no = NULL;

	user_name = gnutr_get_connected_user();

	query = g_strconcat( "SELECT person_no FROM person WHERE ",
		"user_name = '", user_name, "'", NULL);

	person_no = single_ret_val_query_db( query);
	g_assert( person_no);

	g_free( query);
	g_free( user_name);
	return person_no;
}

void
gnutr_write_access_cfg( char *uname, char *pword)
{
	int saved;
	char *home = g_get_home_dir();
	char *pathname;
	xmlDocPtr doc;
	xmlNodePtr cur;

	g_return_if_fail( uname);
	g_return_if_fail( pword);

	/* store the MySQL username and password to file. */
	pathname = g_strconcat( home, "/.gnutrition", NULL);
	gnutr_dir_test( pathname);
	g_free( pathname);
	pathname = g_strconcat( home, "/.gnutrition/mysql_access.xml", NULL);

	doc = xmlNewDoc( "1.0");
	doc->root = xmlNewDocNode( doc, NULL, "Gnutrition", NULL);
	cur = xmlNewChild( doc->root, NULL, "MySQL_Access", NULL);
	xmlNewChild( cur, NULL, "username", uname);
	xmlNewChild( cur, NULL, "password", pword);

	saved = xmlSaveFile( pathname, doc);
	g_assert( saved != -1);
	xmlFreeDoc ( doc);
	g_free( pathname);
}

/* save the name of the person to xml. */
void
gnutr_write_person_name_cfg( char *name)
{
	int saved;
	char *home = g_get_home_dir();
	char *pathname;
	xmlDocPtr doc;
	xmlNodePtr cur;

	g_return_if_fail( name);

	pathname = g_strconcat( home, "/.gnutrition", NULL);
	gnutr_dir_test( pathname);
	g_free( pathname);
	pathname = g_strconcat( home, "/.gnutrition/person_info.xml", NULL);

	doc = xmlNewDoc( "1.0");
	doc->root = xmlNewDocNode( doc, NULL, "Gnutrition", NULL);
	cur = xmlNewChild( doc->root, NULL, "Personal_Info", NULL);
	xmlNewChild( cur, NULL, "Name", name);

	saved = xmlSaveFile( pathname, doc);
	g_assert( saved != -1);
	xmlFreeDoc ( doc);
	g_free( pathname);
}
