////////////////////////////////////////////////////////////////
// Creating the menubar 'Database'
//
// Stefan Liersch: stefan.liersch@googlemail.com, stefan.liersch@ufz.de
// 
// Date:			2006-09-28
// last modified:	2007-06-23
////////////////////////////////////////////////////////////////

//--------------------------------------------------------------
//							ToDo
//--------------------------------------------------------------
//	-	In order to improve the performance of the import and
//		export process of tables it is probably not necessary
//		to use class Csqltable here!
//
// - 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
// - supporting more SQL Field Types
// - Import / Export Field Types not yet harmonising!
// - Implement functions:
//   - On_DB_Create_Table
//   - On_DB_Modify_Table
//	 - GML import and export
//--------------------------------------------------------------

//#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/saga_frame.h"		// location of class Cpgdatabase
										// using global *g_pSAGA_Frame pointer
#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 "pgsql/pg_menu_db.h"

//---------------------------------------------------------------------
// constructor
Cmenu_db::Cmenu_db()
{
	// 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;
	counter += 1;

	m_Menus		= NULL;
	m_nMenus	= 0;

	m_pSSMap	= NULL;
}

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;

	m_Menus		= NULL;
	m_nMenus	= 0;

	m_pSSMap	= NULL;
}
//---------------------------------------------------------------------

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



//---------------------------------------------------------
void Cmenu_db::Destroy(void)
{
	if( m_Menus )
	{
		SG_Free(m_Menus);
		m_Menus		= NULL;
		m_nMenus	= 0;
	}

	delete m_pSSMap;
}

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


///////////////////////////////////////////////////////////////////////
//
//				CREATE DIALOG
//
///////////////////////////////////////////////////////////////////////

//---------------------------------------------------------
void Cmenu_db::Add(wxMenu *pMenu)
{
	m_pDB_Menu = pMenu;

	Create_DB_Menu(pMenu);

	m_Menus	= (wxMenu **)SG_Realloc(m_Menus, (m_nMenus + 1) * sizeof(wxMenu *));
	m_Menus[m_nMenus++]	= pMenu;
}

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

void Cmenu_db::Del(wxMenu* pMenu)
{
	for(int i=0; i<m_nMenus; i++)
	{
		if( m_Menus[i] == pMenu )
		{
			m_nMenus--;

			for( ; i<m_nMenus; i++)
			{
				m_Menus[i]	= m_Menus[i + 1];
			}

			m_Menus	= (wxMenu **)SG_Realloc(m_Menus, m_nMenus * sizeof(wxMenu *));
		}
	}
}
//---------------------------------------------------------


// ID_CMD_MENU_DB_xxx constants are defined in res_commands.h
//---------------------------------------------------------------------
void Cmenu_db::Create_DB_Menu(wxMenu *pMenu)
{
	int		ID_Menu;

    wxMenu* subMenuTable		= new wxMenu;
	wxMenu* subMenuVector		= new wxMenu;
	wxMenu*	subMenuSQL			= new wxMenu;
	wxMenu*	subMenuTimeSeries	= new wxMenu;
	wxMenu*	subMenuHydrology	= new wxMenu;
	wxMenu* subMenuSoilSalinity	= new wxMenu;

	//-----------------------------------------------------
	while( (ID_Menu = pMenu->GetMenuItemCount()) > 0 )
	{
		pMenu->Destroy(pMenu->GetMenuItems().Item(ID_Menu - 1)->GetData());
	}

	//-----------------------------------------------------
	// Connect to Database
	pMenu->Append(ID_CMD_MENU_DB_CONN, wxT("Connect to Database"), 
			_T("Makes a connection to an existing PostgreSQL Database"),false);
	pMenu->AppendSeparator();

	// ++++++++++++++ SUBMENU TABLE ++++++++++++++++++
	subMenuTable->Append(ID_CMD_MENU_DB_IMPORT_TABLE, wxT("Import Table"),
		_T("Import Table from Database"));
	
	subMenuTable->Append(ID_CMD_MENU_DB_EXPORT_TABLE, wxT("Export Table"),
		_T("Export Table to Database"));
	
	subMenuTable->Append(ID_CMD_MENU_DB_CREATE_TABLE, wxT("Create Table"),
		_T("Create Table"));

	subMenuTable->Append(ID_CMD_MENU_DB_MODIFY_TABLE, wxT("Modify Table"),
		_T("Modify Table"));

	subMenuTable->Append(ID_CMD_MENU_DB_DELETE_TABLE, wxT("Delete Table"),
		_T("Export Table to Database"));

	pMenu->Append(ID_CMD_MENU_DB_TABLE, wxT("Table"), subMenuTable);

	// ++++++++++++++ SUBMENU VECTOR ++++++++++++++++++++++
	subMenuVector->Append(ID_CMD_MENU_DB_IMPORTSIMPLEFEATURE, wxT("Import Simple Feature"),
		_T("Import Simple Feature from PostGIS"));

	subMenuVector->Append(ID_CMD_MENU_DB_EXPORTASSIMPLEFEATURE, wxT("Export as Simple Feature"),
		_T("Export Vector Data as OGC Simple Feature"));

	subMenuVector->Append(ID_CMD_MENU_DB_DELETE_SIMPLE_FEATURE, wxT("Delete Simple Feature"),
		_T("Delete Simple Feature from database"));

	pMenu->Append(ID_CMD_MENU_DB_VECTOR, wxT("Vector Data"), subMenuVector);
	pMenu->AppendSeparator();

	// ++++++++++++++ SUBMENU SQL ++++++++++++++++++++++++++
	subMenuSQL->Append(ID_CMD_MENU_DB_CREATE_QUERY, wxT("Create Query"), 
		_T("Executes a user-defined SQL Query"), false);

	subMenuSQL->Append(ID_CMD_MENU_DB_ExecSQLcmd, wxT("Execute SQL Command"), 
		_T("Executes a user-defined SQL Command"), false);

	subMenuSQL->Append(ID_CMD_MENU_DB_CREATE_SPATIALQUERY, wxT("Create Spatial Query"),
		_T("Executes a spatial query"), false);

	pMenu->Append(ID_CMD_MENU_DB_SQL, wxT("SQL"), subMenuSQL);
	pMenu->AppendSeparator();

	// ++++++++++++++ SUBMENU Time Series ++++++++++++++++++
	subMenuTimeSeries->Append(ID_CMD_MENU_DB_TIMESERIES_AUTO, wxT("Time Series Analysis"),
		_T("Automatical time series analysis"));

	subMenuTimeSeries->Append(ID_CMD_MENU_DB_TIMESERIES_AVE, wxT("Average Gauge Data"),
		_T("Average the data from different gauges"));

	pMenu->Append(ID_CMD_MENU_DB_TIMESERIES, wxT("Time Series"), subMenuTimeSeries);
	pMenu->AppendSeparator();

	// ++++++++++++++ SUBMENU Hydrology ++++++++++++++++++
	subMenuHydrology->Append(ID_CMD_MENU_DB_HYDRO_RR_PREPROC, wxT("RR Preprocessing"),
		_T("RR Preprocessing"));

	pMenu->Append(ID_CMD_MENU_DB_HYDROLOGY, wxT("Hydrological Modeling"), subMenuHydrology);
	pMenu->AppendSeparator();

	// ++++++++ SUBMENU Soil Salinity Assessment +++++++++
	subMenuSoilSalinity->Append(ID_CMD_MENU_DB_LOAD_SOILSALINITYMAP, wxT("Load Soil Salinity Assessment Map"),
		_T("Load Soil Salinity Map"));

	subMenuSoilSalinity->AppendSeparator();

	subMenuSoilSalinity->Append(ID_CMD_MENU_DB_CREATE_SOILSALINITYMAP, wxT("Create Soil Salinity Base Map"),
		_T("Create a Soil Salinity Base Map from Shapefile"));

	subMenuSoilSalinity->Append(ID_CMD_MENU_DB_DELETE_SOIL_SALINITY_MAP, wxT("Delete Soil Salinity Assessment Map"),
		_T("Delete Soil Salinity Map"));

	//subMenuSoilSalinity->Append(ID_CMD_MENU_DB_LOAD_SOILSALINITY_RISK_MAP, wxT("Load Soil Salinity Risk Map"),
	//	_T("Load Soil Salinity Risk Map"));
	//
	//subMenuSoilSalinity->AppendSeparator();

	//subMenuSoilSalinity->Append(ID_CMD_MENU_DB_CREATE_CONGRUENCE_MAP, wxT("Create Congruence Map"),
	//	_T("Create Congruence Map"));
	
	pMenu->Append(ID_CMD_MENU_DB_SOILSALINITY, wxT("Soil Salinity Assessment"), subMenuSoilSalinity);
	pMenu->AppendSeparator();


	// ++++++++++++++ MENU Close DB Connection ++++++++++++++++++
	// Close connection to the database
	pMenu->Append(ID_CMD_MENU_DB_DECONN, wxT("Close Database Connection"),
		_T("Exit Database"),false);

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	
	// enable / disable Menu items due to connection status
	_EnableDisableMenu(g_pSAGA_Frame->DB_CONNECTED, pMenu);
}
//---------------------------------------------------------------------

void Cmenu_db::_EnableDisableMenu(bool bconnected, wxMenu* pMenu)
{
	if (bconnected)
	{
		pMenu->Enable(ID_CMD_MENU_DB_CONN, false);
		pMenu->Enable(ID_CMD_MENU_DB_DECONN, true);
		pMenu->Enable(ID_CMD_MENU_DB_TABLE, true);
		pMenu->Enable(ID_CMD_MENU_DB_VECTOR, true);
		pMenu->Enable(ID_CMD_MENU_DB_SQL, true);
		pMenu->Enable(ID_CMD_MENU_DB_TIMESERIES, true);
		pMenu->Enable(ID_CMD_MENU_DB_HYDROLOGY, true);
		pMenu->Enable(ID_CMD_MENU_DB_SOILSALINITY, true);
	} else {
		pMenu->Enable(ID_CMD_MENU_DB_CONN, true);
		pMenu->Enable(ID_CMD_MENU_DB_DECONN, false);
		pMenu->Enable(ID_CMD_MENU_DB_TABLE, false);
		pMenu->Enable(ID_CMD_MENU_DB_VECTOR, false);
		pMenu->Enable(ID_CMD_MENU_DB_SQL, false);
		pMenu->Enable(ID_CMD_MENU_DB_TIMESERIES, false);
		pMenu->Enable(ID_CMD_MENU_DB_HYDROLOGY, false);
		pMenu->Enable(ID_CMD_MENU_DB_SOILSALINITY, false);
	}
}
//---------------------------------------------------------------------


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

void Cmenu_db::On_Command(wxCommandEvent& event)
{
	switch( event.GetId() )
	{
	case ID_CMD_MENU_DB_CONN:
		On_ConnectDB();
		break;
	case ID_CMD_MENU_DB_DECONN:
		On_DeConnectDB();
		break;
	case ID_CMD_MENU_DB_IMPORT_TABLE:
		On_DB_ImportTable();
		break;
	case ID_CMD_MENU_DB_EXPORT_TABLE:
		On_DB_ExportTable();
		break;
	case ID_CMD_MENU_DB_CREATE_TABLE:
		On_DB_CreateTable();
		break;
	case ID_CMD_MENU_DB_DELETE_TABLE:
		On_DB_DeleteTable();
		break;
	case ID_CMD_MENU_DB_MODIFY_TABLE:
		On_DB_ModifyTable();
		break;
	case ID_CMD_MENU_DB_IMPORTSIMPLEFEATURE:
		On_DB_ImportSimpleFeature(SF_CATEGORY_undefined);
		break;
	case ID_CMD_MENU_DB_EXPORTASSIMPLEFEATURE:
		On_DB_ExportAsSimpleFeature();
		break;
	case ID_CMD_MENU_DB_DELETE_SIMPLE_FEATURE:
		On_DB_DeleteSimpleFeature();
		break;
	case ID_CMD_MENU_DB_ExecSQLcmd:
		On_DB_ExecUserSQLCommand();
		break;
	case ID_CMD_MENU_DB_CREATE_QUERY:
		On_DB_CreateQuery();
		break;
	case ID_CMD_MENU_DB_CREATE_SPATIALQUERY:
		On_DB_Create_SpatialQuery();
		break;
	case ID_CMD_MENU_DB_TIMESERIES_AUTO:
		On_DB_TimeSeries_AutoAnalysis();
		break;
	case ID_CMD_MENU_DB_TIMESERIES_AVE:
		On_DB_TimeSeries_Average();
		break;
	case ID_CMD_MENU_DB_HYDRO_RR_PREPROC:
		On_DB_Hydrology_Modeling();
		break;
	case ID_CMD_MENU_DB_CREATE_SOILSALINITYMAP:
		On_DB_Create_SoilSalinity_Base_Map();
		break;
	case ID_CMD_MENU_DB_LOAD_SOILSALINITYMAP:
		On_DB_Load_SoilSalinityMap();
		break;
	case ID_CMD_MENU_DB_DELETE_SOIL_SALINITY_MAP:
		On_DB_Delete_SoilSalinityMap();
		break;
	//case ID_CMD_MENU_DB_LOAD_SOILSALINITY_RISK_MAP:
	//	On_DB_Load_SoilSalinityRiskMap();
	//	break;
	//case ID_CMD_MENU_DB_CREATE_CONGRUENCE_MAP:
	//	On_DB_Create_CongruenceMap();
	//	break;
	}
}

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

void Cmenu_db::On_ConnectDB() //(wxCommandEvent &event)
{
	if (DLG_ConnectDB()) // call user dialog
	{
		_On_ConnectDB();
	}
}
//---------------------------------------------------------------------

void Cmenu_db::On_DeConnectDB()
{
	_On_DeConnectDB();	
}
//---------------------------------------------------------------------



///////////////////////////////////////////////////////////////////////
//
//	Menu Table	
//
///////////////////////////////////////////////////////////////////////

void Cmenu_db::On_DB_ImportTable()
{
	_On_DB_ImportTable();
}

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

void Cmenu_db::On_DB_ExportTable()
{
	// make true if a sql script should be written as text file
	_On_DB_ExportTable(false);
}
//---------------------------------------------------------------------

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

void Cmenu_db::On_DB_DeleteTable()
{
	_On_DB_DeleteTable();
}
//---------------------------------------------------------------------

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



///////////////////////////////////////////////////////////////////////
//
//	SIMPLE FEATURE
//
///////////////////////////////////////////////////////////////////////

void Cmenu_db::On_DB_ImportSimpleFeature(TSG_SF_CATEGORY category)
{
	_On_DB_ImportSimpleFeature(category);
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_ExportAsSimpleFeature()
{
	_On_DB_ExportAsSimpleFeature();
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_DeleteSimpleFeature()
{
	_On_DB_DeleteSimpleFeature();
}
//---------------------------------------------------------------------

///////////////////////////////////////////////////////////////////////
//
//	SQL Commands
//
///////////////////////////////////////////////////////////////////////

void Cmenu_db::On_DB_CreateQuery()
{
	_On_DB_CreateQuery();
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_ExecUserSQLCommand()
{
	_On_DB_ExecUserSQLCommand();
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_Create_SpatialQuery()
{
	_On_DB_Create_SpatialQuery();
}
//---------------------------------------------------------------------



///////////////////////////////////////////////////////////////////////
//
//	TIME SERIES
//
///////////////////////////////////////////////////////////////////////

void Cmenu_db::On_DB_TimeSeries_AutoAnalysis()
{
	_On_DB_TimeSeries_AutoAnalysis();
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_TimeSeries_Average()
{
	_On_DB_TimeSeries_Average();
}
//---------------------------------------------------------------------



///////////////////////////////////////////////////////////////////////
//
//	Hydrological Modelling
//
///////////////////////////////////////////////////////////////////////
//---------------------------------------------------------------------

void Cmenu_db::On_DB_Hydrology_Modeling()
{
	_On_DB_Hydrology_Modeling();
}
//---------------------------------------------------------------------



///////////////////////////////////////////////////////////////////////
//
//	SOIL SALINITY
//
///////////////////////////////////////////////////////////////////////

void Cmenu_db::On_DB_Create_SoilSalinity_Base_Map()
{
	CSG_Data_Object*	pObject;
	CSG_Shapes*			pShapes = Select_Shapefile_for_Export();
	CSG_String			FeatureName;

	if (pShapes != NULL) {

		CSoilSalinityMap* pSSMap = new CSoilSalinityMap(pShapes);

		FeatureName = pSSMap->Get_MapName();
		
		delete pSSMap;
		
		pObject = new CSG_SimpleFeature(g_pSAGA_Frame->db->GetConn(),
			FeatureName.c_str(), g_pSAGA_Frame->db->_Get_GeometryColumnName(FeatureName.c_str()) );

		pObject->asSimpleFeature()->Set_Category(SF_CATEGORY_SoilSalinityMap);

		g_pData->Add(pObject);
	}
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_Delete_SoilSalinityMap()
{
	CSG_String			SF_Name;
	CSG_String			TabName;
	CSG_Parameters		P;

	P.Set_Name(LNG("Delete Soil Salinity Map from PostGIS"));

	P.Add_Choice(
		NULL	, "SF_NAME"	, LNG("Select Soil Salinity Map"),
		"",
		g_pSAGA_Frame->db->GetDBGeometryTables().c_str()
	);
	//-----------------------------------------------------
	
	if( DLG_Parameters(&P) )
	{
		SF_Name	= _GetFeatureNameFromSelection(P("SF_NAME")->asString());
		
		// drop simple feature and delete entry in 'geometry_columns'
		MSG_General_Add(LNG("[MSG] Delete feature..."),true,true);
		_Drop_SimpleFeature(SF_Name);
		MSG_General_Add(LNG("[MSG] ok"),false);

		// drop weights table
		MSG_General_Add(LNG("[MSG] Delete table 'weights'..."),true,true);
		TabName = "_weights_";
		TabName.Append(SF_Name);
		g_pSAGA_Frame->db->DropTable(TabName.c_str());
		MSG_General_Add(LNG("[MSG] ok"),false);

		// drop settings table
		MSG_General_Add(LNG("[MSG] Delete table 'settings'..."),true,true);
		TabName = "_settings_";
		TabName.Append(SF_Name);
		g_pSAGA_Frame->db->DropTable(TabName.c_str());
		MSG_General_Add(LNG("[MSG] ok"),false);

		// drop attribute table
		MSG_General_Add(LNG("[MSG] Delete table 'attributes'..."),true,true);
		TabName = "_attr_";
		TabName.Append(SF_Name);
		g_pSAGA_Frame->db->DropTable(TabName.c_str());
		MSG_General_Add(LNG("[MSG] ok"),false);
	}
}
//---------------------------------------------------------------------

void Cmenu_db::On_DB_Load_SoilSalinityMap()
{
	CSG_Data_Object*	pObject;
	//CSoilSalinityMap*	pSSMap;
	CSG_String			FeatureName;
	CSG_String			GeomName;

	if ( Select_Import_Map(FeatureName, GeomName) ) {
		
		pObject = new CSG_SimpleFeature(g_pSAGA_Frame->db->GetConn(),FeatureName,GeomName.c_str());

		pObject->asSimpleFeature()->Set_Category(SF_CATEGORY_SoilSalinityMap);
		
		g_pData->Add(pObject);

		g_pData->Show(pObject);
	}
}


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



///////////////////////////////////////////////////////////////////////
//
//	
//
///////////////////////////////////////////////////////////////////////

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

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(""));
}
//---------------------------------------------------------------------



///////////////////////////////////////////////////////////////////////
//
//					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"),
		LNG("Use 'localhost' if you want to connect to a local database"),
		"localhost"
	);
	P.Add_String(
		NULL	, "HOSTADDR", LNG("Hostaddress (IP)"),
		LNG("IP address of the server providing the PostgreSQL database"),
		""
	);
	P.Add_String(
		NULL	, "PORT"	, LNG("Port"),
		LNG("Use '5432' to connect to a local database"),
		"5432"
	);
	P.Add_String(
		NULL	, "OPTIONS"	, LNG("Options"),
		"",
		""
	);
	P.Add_String(
		NULL	, "TTY"	, LNG("tty"),
		"",
		""
	);
	P.Add_String(
		NULL	, "DBNAME"	, LNG("Database Name"),
		"",
		"uz_db"
	);
	P.Add_String(
		NULL	, "USER"	, LNG("User"),
		"",
		"postgres"
	);
	P.Add_String(
		NULL	, "PW"		, LNG("Password"),
		"",
		"lierschdb", false, true
	);

	//-----------------------------------------------------
	if( DLG_Parameters(&P) )
	{
		connParms.host		= P("HOST")->asString();
		connParms.hostaddr	= P("HOSTADDR")->asString();
		connParms.port		= P("PORT")->asString();
		connParms.options	= P("OPTIONS")->asString();
		connParms.tty		= P("TTY")->asString();
		connParms.dbname	= P("DBNAME")->asString();
		connParms.user		= P("USER")->asString();
		connParms.password	= P("PW")->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)
		////connParms.password = dialog.GetValue();
		//connParms.password = "lierschdb";

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

CSG_Table *Cmenu_db::SelectSAGATable()
{
	CWKSP_Table_Manager		*pTables;
	CSG_Table				*table;
	CSG_Parameters			P;
	wxString				TableNames;	// Table List
	wxString				TableName;	// Export Table
	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::Add_SAGATableField(int oid, const char* FieldName, CSG_Table *SAGATable)
{
	switch (oid)
	{
	case 16 : // bool
		SAGATable->Add_Field(FieldName, TABLE_FIELDTYPE_Char);
		break;
	case 20 : // INT8
		SAGATable->Add_Field(FieldName, TABLE_FIELDTYPE_Long);
		break;
	case 23 : // INT4
		SAGATable->Add_Field(FieldName, TABLE_FIELDTYPE_Int);
		break;
	case 700 : // FLOAT4
		SAGATable->Add_Field(FieldName, TABLE_FIELDTYPE_Float);
		break;
	case 701 : // FLOAT8
		SAGATable->Add_Field(FieldName, TABLE_FIELDTYPE_Double);
		break;
	case 1082 : // Date
		SAGATable->Add_Field(FieldName, TABLE_FIELDTYPE_String);
		break;
	default :	// String		
		SAGATable->Add_Field(FieldName, TABLE_FIELDTYPE_String);
		break;
	}
}
//---------------------------------------------------------------------

void Cmenu_db::Add_SAGATableRecord(PGresult *res, CSG_Table *SAGATable, int row, int ncols)
{
	int					convi;
	float				convf;
	CSG_Table_Record	*pRecord;

	SAGATable->Add_Record();
	pRecord = SAGATable->Get_Record(row);
	for (int col = 0; col < ncols; col++)
	{
		switch (SAGATable->Get_Field_Type(col))//m_psqltable->GetFieldTypeInt(col))
		{
			case TABLE_FIELDTYPE_Char : // bool
				pRecord->Set_Value(col, PQgetvalue(res,row,col));
				break;
			case TABLE_FIELDTYPE_Long : // INT8
				convi = atoi(PQgetvalue(res,row,col));
				pRecord->Set_Value(col, convi);
				break;	
	
			case TABLE_FIELDTYPE_Int : // INT4
				convi = atoi(PQgetvalue(res,row,col));
				pRecord->Set_Value(col, convi);
				break;	
			case TABLE_FIELDTYPE_Float : // 700 FLOAT4
				convf = atof(PQgetvalue(res,row,col));
				pRecord->Set_Value(col, convf);
				break;	
			case TABLE_FIELDTYPE_Double : // 701 FLOAT8
				convf = convert_sl::StringToDouble(PQgetvalue(res,row,col));
				pRecord->Set_Value(col, convf);
				break;	
			default : // String
				pRecord->Set_Value(col, PQgetvalue(res,row,col));
				break;
		} // end switch
	}
}
//---------------------------------------------------------------------

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());
						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");
		}

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