#include <libgda/libgda.h>

int main()
{
	char table_name[100];
	printf("Table Name: ");
	fflush(stdout);
	scanf("%s", table_name);
	g_print ("Table name: %s\n", table_name);

	gda_init();

	GError* error = NULL;
  
	/*
	  GdaConnection* conn = gda_connection_open_from_string("SQLite", 
	  g_strdup_printf("DB_DIR=.;DB_NAME=%s", table_name), NULL,
	  GDA_CONNECTION_OPTIONS_SQL_IDENTIFIERS_CASE_SENSITIVE, &error);
	*/

	  GdaConnection* conn = gda_connection_open_from_string("PostgreSQL",
								"DB_NAME=glom_example_smallbusiness_v2",
								NULL/*"USERNAME=glom_default_developer_user;PASSWORD=glom_default_developer_password"*/,
								GDA_CONNECTION_OPTIONS_SQL_IDENTIFIERS_CASE_SENSITIVE,
								&error);

	if (error) {
		g_warning("gda_connection_open_from_string() failed: %s\n", error->message);
		g_clear_error(&error);
		return 0;
	}
	
	GdaMetaStore *mstore = gda_meta_store_new_with_file ("store.db");
	g_object_set (G_OBJECT (conn), "meta-store", mstore, NULL);
	g_object_unref (mstore);
	
	/* create table */
	GdaServerProvider* provider = gda_connection_get_provider(conn);
	GdaServerOperation* operation = gda_server_provider_create_operation(provider, conn,
						      GDA_SERVER_OPERATION_CREATE_TABLE, NULL, &error);
	if(error) {
		g_warning("create_operation(CREATE_TABLE) failed: %s\n", error->message);
		g_clear_error(&error);
	}

	gda_server_operation_set_value_at(operation, table_name, NULL, "/TABLE_DEF_P/TABLE_NAME");
	gda_server_operation_set_value_at(operation, "TheId", NULL, "/FIELDS_A/@COLUMN_NAME/0");
	gda_server_operation_set_value_at(operation, "int", NULL, "/FIELDS_A/@COLUMN_TYPE/0");
	gda_server_operation_set_value_at(operation, "TRUE", NULL, "/FIELDS_A/@COLUMN_PKEY/0");

	gda_server_provider_perform_operation(provider, conn, operation, &error);
	if(error) {
		g_warning("perform_operation(CREATE_TABLE) failed: %s\n", error->message);
		g_clear_error(&error);
		return 0;
	}

	/* update meta store */
	g_print ("========= Updating the whole meta store:\n");
	gda_connection_update_meta_store (conn, NULL, NULL);
	
	/* display all tables */
	g_print ("========= ALL tables:\n");
	GdaDataModel* data = gda_connection_get_meta_store_data (conn, GDA_CONNECTION_META_TABLES, NULL, 0);
	gda_data_model_dump(data, stdout);
  
	/* List the fields for this table: */
	GList* list = NULL;
	gchar *tmp;
	tmp = gda_meta_store_sql_identifier_quote (table_name, conn);
	g_print ("========= Fields for table (as *%s* in meta store):\n", tmp);
	list = g_list_prepend(list, gda_holder_new_string("name", tmp));

	GdaDataModel* datamodel_fields = gda_connection_get_meta_store_data_v(conn, 
									      GDA_CONNECTION_META_FIELDS, list,
									      &error);
	if(error) {
		g_warning("get_meta_store_data() failed: %s\n", error->message);
		g_clear_error(&error);
		return 0;
	}
	
	gda_data_model_dump(datamodel_fields, stdout);
  
	return 0;
}
