////////////////////////////////////////////////////////////////
// Creating the menubar 'Database'
//
// Stefan Liersch: stliersch@freenet.de, stefan.liersch@ufz.de
// 2006-09-28
////////////////////////////////////////////////////////////////

//--------------------------------------------------------------
//							ToDo
//--------------------------------------------------------------
// - Connect to database: show a list of available databases
// - add different sql field types in: CreateSAGATable(...)
// - program shuts down if provided with wrong database name
// - program shuts down if provided with wrong table name
// - sometimes program shuts down while disconnecting database 
//   (maybe because a SAGA table is build by SAGA_API)
// - supporting more SQL Field Types
// - Import / Export Field Types not yet harmonising!
// - Implement functions:
//   - On_DB_Create_Table
//   - On_DB_Modify_Table
//	 - all Vector functions
//--------------------------------------------------------------

//#include <wx/textdlg.h>				// using password dialog
#include <vector>
using std::vector;
typedef std::vector<std::string> vector_str;

#include <fstream>		// for test output only	
using std::ofstream;	

// Include private header
#include "saga_gui/res_dialogs.h"		// using DLG_Parameters
#include "saga_gui/res_commands.h"		// Definitions of menu constants (event handler)
#include "saga_gui/wksp_data_manager.h" // adding items to SAGA Workspace *g_pData
#include "wksp_table_manager.h"
#include "wksp_table.h"
#include "saga_gui/helper.h"			// using function MSG_General_Add()
#define MSG_ADD(s)	MSG_General_Add(s, true, true);

#include "saga_gui/saga_frame.h"		// location of class Cpgdatabase
										// using global *g_pSAGA_Frame pointer
#include "PGSQL/menu_db.h"


//#include <iostream>
#include <fstream>
using std::ofstream;

//---------------------------------------------------------------------
int MENU_TABLE  = 450;
int MENU_VECTOR = 451;
//---------------------------------------------------------------------

//---------------------------------------------------------------------
// constructor
Cmenu_db::Cmenu_db(wxMenu *pMenu)
{
	// only the first time when the database menu will be created
	// b_connected should be false
	static int counter = 1;
	if (counter ==1) g_pSAGA_Frame->DB_CONNECTED = false;

	m_pDB_Menu = pMenu;
	Create_DB_Menu(pMenu);
	counter += 1;
}
//---------------------------------------------------------------------

// destructor
Cmenu_db::~Cmenu_db()
{
}

///////////////////////////////////////////////////////////////////////
//
//				PUBLIC MEMBER FUNCTIONS
//
///////////////////////////////////////////////////////////////////////

// ID_CMD_MENU_DB_xxx constants are defined in res_commands.h
//---------------------------------------------------------------------

void Cmenu_db::Create_DB_Menu(wxMenu *m_pDB_Menu)
{
    wxMenu* subMenuTable = new wxMenu;
	wxMenu* subMenuVector = new wxMenu;

	// Connect to Database
	m_pDB_Menu->Append(ID_CMD_MENU_DB_CONN, wxT("Connect to Database"), 
			_T("Makes a connection to an existing PostgreSQL Database"),false);
	
	// ++++++++++++++ SUBMENU TABLE ++++++++++++++++++
	// Submenu 'Import Table' for Menu 'Table'
	subMenuTable->Append(ID_CMD_MENU_DB_IMPORT_TABLE, wxT("Import Table"),
		_T("Import Table from Database"));
	// Submenu 'Export Table' for Menu 'Table'
	subMenuTable->Append(ID_CMD_MENU_DB_EXPORT_TABLE, wxT("Export Table"),
		_T("Export Table to Database"));
	// Submenu 'Create Table' for Menu 'Table'
	subMenuTable->Append(ID_CMD_MENU_DB_CREATE_TABLE, wxT("Create Table"),
		_T("Create Table"));
	// Submenu 'Delete Table' for Menu 'Table'
	subMenuTable->Append(ID_CMD_MENU_DB_MODIFY_TABLE, wxT("Modify Table"),
		_T("Modify Table"));
	// Submenu 'Export Table' for Menu 'Table'
	subMenuTable->Append(ID_CMD_MENU_DB_DELETE_TABLE, wxT("Delete Table"),
		_T("Export Table to Database"));
	// Append submenu to menu 'Table'
	m_pDB_Menu->Append(MENU_TABLE, wxT("Table"), subMenuTable);

	// ++++++++++++++ SUBMENU VECTOR ++++++++++++++++++
	// Sumbmenu 'Import Shape' for Menu 'Vector Data'
	subMenuVector->Append(ID_CMD_MENU_DB_IMPORTSIMPLEFEATURE, wxT("Import Simple Feature"),
		_T("Import Simple Feature from PostGIS"));
	subMenuVector->Append(ID_CMD_MENU_DB_IMPORTASSHAPE, wxT("Import Shape from Database"),
		_T("Import Vector Data as Shape file"));
	// Sumbmenu 'Export Shape' for Menu 'Vector Data'
	subMenuVector->Append(ID_CMD_MENU_DB_EXPORTASSHAPE, wxT("Export Shape to Database"),
		_T("Export Vector Data as Shape file"));
	// Sumbmenu 'Import GML' for Menu 'Vector Data'
	subMenuVector->Append(ID_CMD_MENU_DB_IMPORTASGML, wxT("Import as GML from Database"),
		_T("Import Vector Data as GML file"));
	// Sumbmenu 'Export GML' for Menu 'Vector Data'
	subMenuVector->Append(ID_CMD_MENU_DB_EXPORTASGML, wxT("Export as GML to Database"),
		_T("Export Vector Data as GML file"));
	// Sumbmenu 'Export Simple Feature' for Menu 'Vector Data'
	subMenuVector->Append(ID_CMD_MENU_DB_EXPORTASSIMPLEFEATURE, wxT("Export as Simple Feature"),
		_T("Export Vector Data as OGC Simple Feature"));
	// Append submenu to menu 'Vector Data'
	m_pDB_Menu->Append(MENU_VECTOR, wxT("Vector Data"), subMenuVector);
	
	// Close connection to the database
	m_pDB_Menu->AppendSeparator();
	m_pDB_Menu->Append(ID_CMD_MENU_DB_DECONN, wxT("Close Database Connection"),
		_T("Exit Database"),false);
	
	// enable / disable Menu items due to connection status
	if (g_pSAGA_Frame->DB_CONNECTED)
	{
		m_pDB_Menu->Enable(ID_CMD_MENU_DB_CONN, false);
		m_pDB_Menu->Enable(ID_CMD_MENU_DB_DECONN, true);
		m_pDB_Menu->Enable(MENU_TABLE, true);
		m_pDB_Menu->Enable(MENU_VECTOR, true);
	} else {
		m_pDB_Menu->Enable(ID_CMD_MENU_DB_CONN, true);
		m_pDB_Menu->Enable(ID_CMD_MENU_DB_DECONN, false);
		m_pDB_Menu->Enable(MENU_TABLE, false);
		m_pDB_Menu->Enable(MENU_VECTOR, false);
	}
}
//---------------------------------------------------------------------

//////////////////////////////////////////////////////////
// MENU EVENT FUNCTIONS: routed from saga_frame.cpp
//////////////////////////////////////////////////////////
//---------------------------------------------------------------------

void Cmenu_db::On_ConnectDB() //(wxCommandEvent &event)
{
	if (DLG_ConnectDB()) // call user dialog
	{
		try
		{
			// db object must be destroyed (but when and where)??????
			g_pSAGA_Frame->db = new Cpgdatabase();

			// make a connection to the database
			if (g_pSAGA_Frame->db->ConnectToDB(host.c_str(),port.c_str(),
								options.c_str(),tty.c_str(),
								dbname.c_str(),user.c_str(),password.c_str()))
			{
				g_pSAGA_Frame->DB_CONNECTED = true;
				MSG_ADD(wxString::Format("%s%s%s","Database ", dbname.c_str(), " connected"));
				// enable / disable Menu items due to connection status
				m_pDB_Menu->Enable(ID_CMD_MENU_DB_CONN, false);
				m_pDB_Menu->Enable(ID_CMD_MENU_DB_DECONN, true);
				m_pDB_Menu->Enable(MENU_TABLE, true);
				m_pDB_Menu->Enable(MENU_VECTOR, true);
			} else {
				g_pSAGA_Frame->DB_CONNECTED = false;
				MSG_ADD(wxString::Format("%s%s%s","Database ", dbname.c_str(), " not connected"));
				// enable / disable Menu items due to connection status
				m_pDB_Menu->Enable(ID_CMD_MENU_DB_CONN, true);
				m_pDB_Menu->Enable(ID_CMD_MENU_DB_CONN, false);
				m_pDB_Menu->Enable(MENU_TABLE, false);
				m_pDB_Menu->Enable(MENU_VECTOR, true);
				g_pSAGA_Frame->db->ExitDB();
			}
		}
		catch(...)
		{
			MSG_ADD("Connecting Database not successfull!");
		}
	}
}
//---------------------------------------------------------------------

void Cmenu_db::On_DeConnectDB()
{
	g_pSAGA_Frame->db->ExitDB();
	MSG_ADD(wxString::Format("%s%s%s","Database ", dbname.c_str(), " disconnected"));
	g_pSAGA_Frame->DB_CONNECTED = false;
	
	// enable / disable Menu items due to connection status
	m_pDB_Menu->Enable(ID_CMD_MENU_DB_CONN, true);
	m_pDB_Menu->Enable(ID_CMD_MENU_DB_DECONN, false);
	m_pDB_Menu->Enable(MENU_TABLE, false);
	m_pDB_Menu->Enable(MENU_VECTOR, false);
	
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_ImportTable()
{
	//Csqltable	*SQLTable;
	CSG_Table		*pTable;
	//-----------------------------------------------------
	// DIALOG
	//-----------------------------------------------------
	string		tablename;
	CSG_Parameters	P;

	P.Set_Name(LNG("Import Table from Database"));

	P.Add_Choice(
		NULL	, "TABLE"	, LNG("Select Import Table"),
		"",
		g_pSAGA_Frame->db->GetDBTables().c_str()
	);

	//-----------------------------------------------------
	if( DLG_Parameters(&P) )
	{
		try
		{
			tablename	= P("TABLE")->asString();

			m_psqltable = new Csqltable(tablename,
									 g_pSAGA_Frame->db->GetNumberCols(tablename.c_str()),
									 g_pSAGA_Frame->db->GetNumberRows(tablename.c_str()));

			if (g_pSAGA_Frame->db->ReadTable(m_psqltable))
			{
				MSG_ADD("Read Table successfull");
				//-----------------------------------------------------
				// create SAGA Table from database table

				pTable = SG_Create_Table();
				//pTable = new CSG_Table();

				CreateSAGATable(m_psqltable, pTable);
				
				// add table to SAGA Workspace
				pTable->Set_Name(tablename.c_str());
				g_pData->Add(pTable);

				delete m_psqltable;

			} else {
				MSG_ADD("Read Table not successfull");
			}

		}
		catch(...)
		{
			MSG_ADD("Read Table not successfull");
		}

	} // end if (DLG_Parameters(...))
	//g_pSAGA_Frame->DB_CONNECTED = true;
}

//---------------------------------------------------------------------

void Cmenu_db::On_DB_ExportTable()
{
	CSG_Table			*pTable;
	Csqltable			*SQLTable;
	ESG_Table_FieldType	FType; // SAGA_API/table.h
	//string				record;
	char				record[4096];
	char				del[4096] = "";
	CSG_String			val;
	int					i;
	
	// select table to export from SAGA workspace
	try
	{
		pTable = SelectSAGATable();
	}
	catch(...)
	{
	}
	if (pTable == NULL)
	{
		MSG_ADD("Select table failed");
	} else {
		MSG_ADD(pTable->Get_Name());
		// prepare SQLTable Fields to be created
		SQLTable = new Csqltable(pTable->Get_Name(),
								pTable->Get_Field_Count(),
								pTable->Get_Record_Count());

		// define sqltable field names and types
		for (i = 0; i < pTable->Get_Field_Count(); i++)
		{
			SQLTable->SetFieldName(pTable->Get_Field_Name(i),i);// = (pTable->Get_Field_Name(i));
			FType			= (pTable->Get_Field_Type(i));
			switch (FType)
			{
				case TABLE_FIELDTYPE_Char :
					SQLTable->SetFieldType("CHAR",i);
					break;
				case TABLE_FIELDTYPE_String :
					SQLTable->SetFieldType("VARCHAR",i);
					break;
				case TABLE_FIELDTYPE_Short :
					SQLTable->SetFieldType("INT4",i);
					break;
				case TABLE_FIELDTYPE_Int :
					SQLTable->SetFieldType("INT8",i);
					break;
				case TABLE_FIELDTYPE_Long :
					SQLTable->SetFieldType("INT8",i);
					break;
				case TABLE_FIELDTYPE_Float :
					SQLTable->SetFieldType("FLOAT4",i);
					break;
				case TABLE_FIELDTYPE_Double :
					SQLTable->SetFieldType("FLOAT8",i);
					break;
				default : SQLTable->SetFieldType("VARCHAR",i);
			} // end switch
		}

		// create table fields in current PostgreSQL database
		if (g_pSAGA_Frame->db->CreateTable(SQLTable))
		{
			MSG_ADD("Create Table successfull");
		} else {
			MSG_ADD("Create Table not successfull");
		}

		// create records / insert values into table matrix
		for (int y = 0; y < pTable->Get_Record_Count(); y++)
		{
			strcpy(record,del); // delete variable record
			for (int x = 0; x < pTable->Get_Field_Count(); x++)
			{
				FType = (pTable->Get_Field_Type(x));
				switch (FType)
				{
					case TABLE_FIELDTYPE_Char :
						strcat(record,"'");
						strcat(record,pTable->Get_Record(y)->asString(x));
						strcat(record,"'");
						if (x + 1 < pTable->Get_Field_Count()) strcat(record, ",");
						break;
					case TABLE_FIELDTYPE_String :
						strcat(record,"'");
						strcat(record,pTable->Get_Record(y)->asString(x));
						strcat(record,"'");
						if (x + 1 < pTable->Get_Field_Count()) strcat(record, ",");
						break;
					case TABLE_FIELDTYPE_Short :
						strcat(record,pTable->Get_Record(y)->asString(x));
						if (x + 1 < pTable->Get_Field_Count()) strcat(record, ",");
						break;
					case TABLE_FIELDTYPE_Int :
						strcat(record,pTable->Get_Record(y)->asString(x));
						if (x + 1 < pTable->Get_Field_Count()) strcat(record, ",");
						break;
					case TABLE_FIELDTYPE_Long :
						strcat(record,pTable->Get_Record(y)->asString(x));
						if (x + 1 < pTable->Get_Field_Count()) strcat(record, ",");
						break;
					case TABLE_FIELDTYPE_Float :
						strcat(record,pTable->Get_Record(y)->asString(x));
						if (x + 1 < pTable->Get_Field_Count()) strcat(record, ",");
						break;
					case TABLE_FIELDTYPE_Double :
						strcat(record,pTable->Get_Record(y)->asString(x));
						if (x + 1 < pTable->Get_Field_Count()) strcat(record, ",");
						break;
					default:
						strcat(record,"'");
						strcat(record,pTable->Get_Record(y)->asString(x));
						strcat(record,"'");
						if (x + 1 < pTable->Get_Field_Count()) strcat(record, ",");
						break;
				} // end switch

			} // end if (int x...

			// insert values into table
			g_pSAGA_Frame->db->InsertIntoTable(SQLTable->GetTableName().c_str(), record);
		} // end if (int y...
	}
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_CreateTable()
{
	wxMessageBox("Not yet implemented", wxT(""));
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_DeleteTable()
{
	wxString		tablename;
	CSG_Parameters	P;

	P.Set_Name(LNG("Delete Table from Database"));

	P.Add_Choice(
		NULL	, "TABLE"	, LNG("Select Import Table"),
		"",
		g_pSAGA_Frame->db->GetDBTables().c_str()
	);

	//-----------------------------------------------------
	if( DLG_Parameters(&P) )
	{
		tablename	= P("TABLE")->asString();

		if (g_pSAGA_Frame->db->DropTable(tablename.c_str()))
		{
			MSG_ADD("Table deleted");
		}
		else {
			MSG_ADD("Failed to delete table");
		}
	}
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_ModifyTable()
{
	wxMessageBox("Not yet implemented", wxT(""));
}

//---------------------------------------------------------------------

void Cmenu_db::On_DB_ImportSimpleFeature()
{
	ofstream file("SimpleFeature.txt");

	CSG_Table	*pTable;
	CSG_Shapes	*pShapes_SF; // Shapefile imported from SimpleFeature
	CSG_Data_Object		*pObject;

	//-----------------------------------------------------
	// DIALOG
	//-----------------------------------------------------
	string		tablename;
	CSG_Parameters	P;

	P.Set_Name(LNG("Import Simple Feature from PostGIS"));

	P.Add_Choice(
		NULL	, "SF_NAME"	, LNG("Select Simple Feature"),
		"",
		g_pSAGA_Frame->db->GetDBGeometryTables().c_str()
	);


	//-----------------------------------------------------
	if( DLG_Parameters(&P) )
	{
		try
		{
			tablename	= P("SF_NAME")->asString();

			SimpleFeature = new CSimpleFeature(g_pSAGA_Frame->db->GetConn(),
											   tablename.c_str());

			// create shape layer
			pShapes_SF = SG_Create_Shapes();
			// assign SimpleFeature data to shape layer
			create_shape_fromSF(pShapes_SF);
			// add shape layer to SAGA Workspace
			pObject = new CSG_Shapes(*pShapes_SF);
			g_pData->Add(pObject);
	
		}
		catch(...)
		{
			//return(false);
		}
		MSG_ADD(wxString::Format("%s%s","SF_TGeometry: ", SimpleFeature->GetGeoType_asString().c_str()));
		MSG_ADD(wxString::Format("%s%d","nFeatures: ",SimpleFeature->GetNumFeatures()));
		MSG_ADD(wxString::Format("%s%d","nPoints:   ",SimpleFeature->GetTotalNumPoints()));
		
		for (int feature = 0; feature < SimpleFeature->GetNumFeatures(); feature++)
		{
			for (int x = 0; x < SimpleFeature->GetNumPointsFeature(feature); x++)
			{
				MSG_ADD(wxString::Format("%s%10.2f%s%10.2f","x: ",SimpleFeature->Get_X_Value(feature,x)," y: ",SimpleFeature->Get_Y_Value(feature,x)));
				//MSG_ADD(wxString::Format("%s%10.2f","y: ",SimpleFeature->SF_Point[feature][x].y));
			}
		}

		// test output in file SimpleFeature.txt
		file << "FeatureName: " << SimpleFeature->GetFeatureName() << endl;
		file << "TableCatalog: " << SimpleFeature->GetTableCatalog() << endl;
		file << "TableSchema: " << SimpleFeature->GetTableSchema() << endl;
		file << "GeometryColumnName: " << SimpleFeature->GetGeometryColumnName() << endl;
		file << "GeometryColumnNumber: " << SimpleFeature->GetGeometryColumnNumber() << endl;
		file << "CoordDimension: " << SimpleFeature->GetCoordDimension() << endl;
		file << "SRID: " << SimpleFeature->GetSRID() << endl;
		file << "SRID_asString: " << SimpleFeature->GetSRID_asString() << endl;
		file << "GeoType_asString: " << SimpleFeature->GetGeoType_asString() <<  endl;
		file << "GeoType: " << SimpleFeature->GetGeoType() << endl;
		file << "NN: " << SimpleFeature->GetNN() << endl;
		file << "SRID_PK: " << SimpleFeature->GetSRID_PK() << endl;
		file << "Auth_Name: " << SimpleFeature->GetAuth_Name() << endl;
		file << "Auth_SRID: " << SimpleFeature->GetAuth_SRID() << endl;
		file << "srText: " << SimpleFeature->GetsrText() << endl;
		file << "proj4text: " << SimpleFeature->Getproj4text() << endl << endl;
		file << "Feature Table Attributes" << endl;

		for (int col = 0; col < SimpleFeature->Get_ncols(); col++)
		{
			file << "ColumnName: " << SimpleFeature->GetFieldName(col);
			file << ",  ColumnType: " << SimpleFeature->GetFieldType(col);
			for (int row = 0; row < SimpleFeature->Get_nrows(); row++)
				file << ",  Value: " << SimpleFeature->GetValue(col,row) << endl;
		}

		file << endl;
		file << "Geometry Features" << endl;
		file << "Number of Features: " << SimpleFeature->GetNumFeatures() << endl;
		file << "Total Number of Points: " << SimpleFeature->GetTotalNumPoints() << endl;
		file << "WKT: " << SimpleFeature->GetWKT() << endl;
		file << "ETYPE: " << SimpleFeature->GetETYPE() << endl << endl;

		for (int feature = 0; feature < SimpleFeature->GetNumFeatures(); feature++)
		{
			file << "Feature Number: " << feature << endl;
			for (int point = 0; point < SimpleFeature->GetNumPointsFeature(feature); point++)
			{
				file << "x: " << SimpleFeature->Get_X_Value(feature,point);
				file << ",  y: " << SimpleFeature->Get_Y_Value(feature,point) << endl;
			}
		}

	}
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_ImportAsShape()
{
	wxMessageBox("Not yet implemented", wxT(""));
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_ExportAsShape()
{
	wxMessageBox("Not yet implemented", wxT(""));
}

//---------------------------------------------------------------------

void Cmenu_db::On_DB_ImportAsGML()
{
	wxMessageBox("Not yet implemented", wxT(""));
}

//---------------------------------------------------------------------

void Cmenu_db::On_DB_ExportAsGML()
{
	wxMessageBox("Not yet implemented", wxT(""));
}

//---------------------------------------------------------------------

void Cmenu_db::On_DB_ExportAsSimpleFeature()
{
	wxMessageBox("Not yet implemented", wxT(""));
}

///////////////////////////////////////////////////////////////////////
//
//					PRIVATE MEMBER FUNCTIONS
//
///////////////////////////////////////////////////////////////////////


//---------------------------------------------------------------------
//								DIALOGS
//---------------------------------------------------------------------
bool Cmenu_db::DLG_ConnectDB()
{
	CSG_Parameters	P;

	P.Set_Name(LNG("Connect to Database"));

	P.Add_String(
		NULL	, "HOST"	, LNG("Host"),
		"",
		"localhost"
	);
	P.Add_String(
		NULL	, "PORT"	, LNG("Port"),
		"",
		"5432"
	);
	P.Add_String(
		NULL	, "OPTIONS"	, LNG("Options"),
		"",
		""
	);
	P.Add_String(
		NULL	, "TTY"	, LNG("tty"),
		"",
		""
	);
	P.Add_String(
		NULL	, "DBNAME"	, LNG("Database Name"),
		"",
		"firstdb"
	);
	P.Add_String(
		NULL	, "USER"	, LNG("User"),
		"",
		"dbliersch"
	);

	//-----------------------------------------------------
	if( DLG_Parameters(&P) )
	{
		host		= P("HOST")->asString();
		port		= P("PORT")->asString();
		options		= P("OPTIONS")->asString();
		tty			= P("TTY")->asString();
		dbname		= P("DBNAME")->asString();
		user		= P("USER")->asString();
		
		// Password dialog
		wxPasswordEntryDialog dialog(g_pSAGA_Frame,
				wxT("Please type in your password"),
				wxT("Password for database login"),
				wxT(""),
				wxOK | wxCANCEL);
		if (dialog.ShowModal() == wxID_OK)
		//password = dialog.GetValue();
		password = "lierschdb";

		return(true);
	} else {
		return(false);
	}
}
//---------------------------------------------------------------------

CSG_Table *Cmenu_db::SelectSAGATable()
{
	CWKSP_Table_Manager		*pTables;
	CSG_Table				*table;
	CSG_Parameters			P;
	wxString				TableNames;
	wxString				TableName;
	wxString				newName;

	if ( (pTables = g_pData->Get_Tables()) !=NULL)
	{
		for (int i = 0; i < pTables->Get_Count(); i++)
		{
			TableNames.Append(pTables->Get_Table(i)->Get_Name());
			TableNames.Append("|");
		}
	}

	P.Set_Name(LNG("Select Table"));

	P.Add_Choice(
		NULL	, "TABLE"	, LNG("Select Table for export"),
		"",
		TableNames
	);
	P.Add_String(
		NULL	, "NAME"	, LNG("Export Table Name"),
		"",
		""
	);

	if( DLG_Parameters(&P) )
	{
		TableName = P("TABLE")->asString();
		newName	  = P("NAME")->asString();
		for (int i = 0; i < pTables->Get_Count(); i++)
		{
			if (!strcmp(TableName,pTables->Get_Table(i)->Get_Name()))
				table = pTables->Get_Table(i)->Get_Table();
		}
		if (newName != "") table->Set_Name(newName.c_str());
		return(table);
	} else {
		return(NULL);
	}

}
//---------------------------------------------------------------------

void Cmenu_db::CreateSAGATable(Csqltable *m_psqltable, CSG_Table *SAGATable)
{
	int i, x, y;
	int convi;
	float convf;

	CSG_Table_Record *pRecord;

	// creating column titles and types
	try
	{
		for (i = 0; i < m_psqltable->Get_ncols(); i++)
		{
			switch (m_psqltable->GetFieldTypeInt(i))
			{
			case 16 : // bool
				SAGATable->Add_Field(m_psqltable->GetFieldName(i).c_str(), TABLE_FIELDTYPE_Char);
				break;
			case 20 : // INT8
				SAGATable->Add_Field(m_psqltable->GetFieldName(i).c_str(), TABLE_FIELDTYPE_Long);
				break;
			case 23 : // INT4
				SAGATable->Add_Field(m_psqltable->GetFieldName(i).c_str(), TABLE_FIELDTYPE_Int);
				break;
			case 700 : // FLOAT4
				SAGATable->Add_Field(m_psqltable->GetFieldName(i).c_str(), TABLE_FIELDTYPE_Float);
				break;
			case 701 : // FLOAT8
				SAGATable->Add_Field(m_psqltable->GetFieldName(i).c_str(), TABLE_FIELDTYPE_Double);
				break;
			case 1082 : // Date
				SAGATable->Add_Field(m_psqltable->GetFieldName(i).c_str(), TABLE_FIELDTYPE_String);
				break;
			default :	// String		
				SAGATable->Add_Field(m_psqltable->GetFieldName(i).c_str(), TABLE_FIELDTYPE_String);
				break;
			}
		}

		// add values to the table
		for (y = 0; y < m_psqltable->Get_nrows(); y++)
		{
			SAGATable->Add_Record();
			pRecord = SAGATable->Get_Record(y);
			for (x = 0; x < m_psqltable->Get_ncols(); x++)
			{
				switch (m_psqltable->GetFieldTypeInt(x))
				{
					case 16 : // bool
						pRecord->Set_Value(x, m_psqltable->GetValue(x,y).c_str());//matrix[x][y].c_str());
						break;
					case 20 : // INT8
						convi = atoi(m_psqltable->GetValue(x,y).c_str());
						pRecord->Set_Value(x, convi);
						break;			
					case 23 : // INT4
						convi = atoi(m_psqltable->GetValue(x,y).c_str());
						pRecord->Set_Value(x, convi);
						break;	
					case 700 : // FLOAT4
						convf = atof(m_psqltable->GetValue(x,y).c_str());
						pRecord->Set_Value(x, convf);
						break;	
					case 701 : // FLOAT8
						convf = atof(m_psqltable->GetValue(x,y).c_str());
						pRecord->Set_Value(x, convf);
						break;	
					default : // String
						pRecord->Set_Value(x, m_psqltable->GetValue(x,y).c_str());
						break;
				} // end switch2
			}
		}
	} // end try
	catch(...)
		{
			MSG_ADD("CreateSAGATable not successfull");
		}

}
//---------------------------------------------------------------------
