/* Forms/Read-write form
 *
 * The GnomeDbForm widget displays data stored in a GdaDataModel.
 */

#include <libgnomedb/libgnomedb.h>

extern GdaDict *demo_dict;
static GtkWidget *window = NULL;

GtkWidget *
do_form_rw (GtkWidget *do_widget)
{  
	if (!window) {
                GdaQuery *query;
		GtkWidget *vbox;
		GtkWidget *label;
		GdaDataModel *model;
		GtkWidget *form;
		
		window = gtk_dialog_new_with_buttons ("GnomeDbForm (RW)",
						      GTK_WINDOW (do_widget),
						      0,
						      GTK_STOCK_CLOSE,
						      GTK_RESPONSE_NONE,
						      NULL);
		
		g_signal_connect (window, "response",
				  G_CALLBACK (gtk_widget_destroy), NULL);
		g_signal_connect (window, "destroy",
				  G_CALLBACK (gtk_widget_destroyed), &window);
		
		vbox = gtk_vbox_new (FALSE, 5);
		gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->vbox), vbox, TRUE, TRUE, 0);
		gtk_container_set_border_width (GTK_CONTAINER (vbox), 5);
		
		label = gtk_label_new ("The following GnomeDbForm widget displays data from the 'products' table.\n\n"
				       "As modification queries are provided, the data is read-write\n(except for the 'price' "
				       "field as these queries voluntarily omit that field).");
		gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);
		
		/* Create the demo widget */
                query = gda_query_new_from_sql (demo_dict, "SELECT ref, category, name, price, wh_stored FROM products", NULL);
		model = gda_data_model_query_new (query);
		g_object_unref (query);

		gda_data_model_query_set_modification_query (GDA_DATA_MODEL_QUERY (model),
							     "UPDATE products set "
							     "ref=##/*name:'+0' type:gchararray*/, "
							     "category=##/*name:'+1' type:gint*/,"
							     "name=##/*name:'+2' type:gchararray*/, "
							     "wh_stored=##/*name:'+4' type:gint*/ "
							     "WHERE ref=##/*name:'-0' type:gchararray*/", NULL);
		gda_data_model_query_set_modification_query (GDA_DATA_MODEL_QUERY (model),
							     "DELETE FROM products WHERE ref=##/*name:'-0' type:gchararray*/", NULL);
		gda_data_model_query_set_modification_query (GDA_DATA_MODEL_QUERY (model),
							     "INSERT INTO products (ref, category, name, price, wh_stored) "
							     "VALUES (##/*name:'+0' type:gchararray*/, "
							     "##/*name:'+1' type:gint*/, "
							     "##/*name:'+2' type:gchararray*/, "
							     "1.0, "
							     "##/*name:'+4' type:gint*/)", NULL);

		form = gnome_db_form_new (model);
		g_object_unref (model);

		gtk_box_pack_start (GTK_BOX (vbox), form, TRUE, TRUE, 0);
	}

	if (!GTK_WIDGET_VISIBLE (window))
		gtk_widget_show_all (window);
	else
		gtk_widget_destroy (window);

	return window;
}


