///////////////////////////////////////////////////////////
// Author:			Stefan Liersch
// Contact:			stefan.liersch@googlemail.com,
//					stefan.liersch@ufz.de
//
// Date:			2007-06-20
// last modified:	2007-06-21
//
//---------------------------------------------------------
// DESCRIPTION
//---------------------------------------------------------
//
//---------------------------------------------------------
// ToDo
//---------------------------------------------------------
//	-	Dialog verbessern
//		- SRID als Zahl wählbar, bei bedarf ausgelagerter Selektions-Dialog
//	-	Include Shape file select
//	-	SRID information should be structured (projected / not projected...)
//	-	Tool Tips
//	-	Get_SRID(): int row = selected_rows[0]; (kann abstürzen)
//	-	SimpleFeature name: check if name is a valid postgres name
//
///////////////////////////////////////////////////////////

#include "libpq-fe.h"

#include "saga_gui/helper.h"
#include "saga_gui/simplefeature_export_dlg.h"
#include "pgsql/dialogs/simplefeature_export_dlg_srid.h"

#include "saga_gui/wksp_data_manager.h" // adding items to SAGA Workspace *g_pData
#include "wksp_shapes_manager.h"
#include "wksp_shapes.h"

//#include "saga_gui/wksp_data_manager.h"

#include <fstream>

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

BEGIN_EVENT_TABLE(CSimpleFeature_export_dlg, wxDialog)
	EVT_RADIOBUTTON(ID_RADIOBUTTON_create_pk,		CSimpleFeature_export_dlg::On_RadioButtonSelected_pk)
	EVT_RADIOBUTTON(ID_RADIOBUTTON_Select_pk_column,CSimpleFeature_export_dlg::On_RadioButtonSelected_pk)

	EVT_BUTTON(ID_ButtonSRID_p,						CSimpleFeature_export_dlg::On_ButtonSRID_p)
	EVT_BUTTON(ID_ButtonSRID_g,						CSimpleFeature_export_dlg::On_ButtonSRID_g)
END_EVENT_TABLE()

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

CSimpleFeature_export_dlg::CSimpleFeature_export_dlg(wxWindow *parent, wxWindowID id, const wxString &title,
													 CSG_Shapes *pShapes)
													: wxDialog(parent, id, title,
													  wxPoint(100,100), //wxDefaultPosition,
													  wxDefaultSize,
													  wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
{
	m_pShapes	= pShapes;

	// cut off the file extension from Shapefile name
	wxString m_pot_ShapeName = "";
	m_potShapeName.insert(0, m_pShapes->Get_Name());
	m_potShapeName = _Get_Reduced_ShapeName(m_potShapeName);

	_CreateDLG();
	//m_pTextCtrl_pk_colname->Disable();
}
//---------------------------------------------------------------------

CSimpleFeature_export_dlg::~CSimpleFeature_export_dlg()
{
}
//---------------------------------------------------------------------

///////////////////////////////////////////////////////////////////////
//
//	GET FUNCTIONS
//
///////////////////////////////////////////////////////////////////////

//---------------------------------------------------------------------
wxString CSimpleFeature_export_dlg::Get_SimpleFeatureName()
{
	m_pTextCtrl_SFname->SetSelection(0,100);
	return (m_pTextCtrl_SFname->GetStringSelection());
}
//---------------------------------------------------------------------
int CSimpleFeature_export_dlg::Get_PK_ColNumber()
{
	if (m_pRadioButton_select_pk->GetValue())
	{
		int pk_col = 0;
		wxString selFieldName = m_pChoice_pk_col->GetString(m_pChoice_pk_col->GetSelection());

		for (int i = 0; i < m_pShapes->Get_Table().Get_Field_Count(); i++)
		{
			if (!selFieldName.CmpNoCase(m_pShapes->Get_Table().Get_Field_Name(i)))
			{
				pk_col = i;
			}
		}

		return(pk_col);
	}
	else
		return(-1);
}

//---------------------------------------------------------------------
int CSimpleFeature_export_dlg::Get_SRID()
{
	m_pTextCtrl_SRID->SetSelection(0,100);
	return(convert_sl::StringToInt(m_pTextCtrl_SRID->GetStringSelection().c_str()));
}
//---------------------------------------------------------------------
wxString CSimpleFeature_export_dlg::Get_TableCatalog()
{
	m_pTextCtrl_catalog->SetSelection(0,100);
	return (m_pTextCtrl_catalog->GetStringSelection());
}
//---------------------------------------------------------------------
wxString CSimpleFeature_export_dlg::Get_TableSchema()
{
	return (m_pComboBox_schema->GetStringSelection());
}
//---------------------------------------------------------------------
wxString CSimpleFeature_export_dlg::Get_GeometryColumn()
{
	m_pTextCtrl_geometrycolumn->SetSelection(0,100);
	return (m_pTextCtrl_geometrycolumn->GetStringSelection());
}
//---------------------------------------------------------------------
int CSimpleFeature_export_dlg::Get_CoordDimension()
{
	return (atoi(m_pComboBox_coorddimension->GetStringSelection()));
}
//---------------------------------------------------------------------

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

wxString CSimpleFeature_export_dlg::_Get_Reduced_ShapeName(wxString &ShapeName)
{
	//unsigned int pos = 0;
	//for (pos = 0; ShapeName[pos] != '0'; pos++) {
	//	if (ShapeName[pos] == '.')
	//		return(ShapeName.substr(0,pos));
	//}
	//return(ShapeName);

	return( ShapeName.substr(0,ShapeName.find(".")) );
}
//---------------------------------------------------------------------

///////////////////////////////////////////////////////////////////////
//
//	CREATE DIALOG
//
///////////////////////////////////////////////////////////////////////
//---------------------------------------------------------------------
void CSimpleFeature_export_dlg::_CreateDLG()
{
    wxBoxSizer *MainBoxSizer = new wxBoxSizer( wxVERTICAL );

	//-------------------------------------------
	// Static Box: SimpleFeature name
	//-------------------------------------------
	wxStaticBox *statBoxname = new wxStaticBox( this, -1, wxT("SimpleFeature Name") );
	statBoxname->SetFont( wxFont( 8, wxSWISS, wxNORMAL, wxBOLD ) );
    wxStaticBoxSizer *statBoxSizer_SFname = new wxStaticBoxSizer( statBoxname, wxHORIZONTAL );

	wxBoxSizer *item41 = new wxBoxSizer( wxHORIZONTAL );
	wxStaticText *txt_SFname = new wxStaticText( this, ID_TEXT, wxT("Name:"), wxDefaultPosition, wxSize(150,-1), 0 );
    m_pTextCtrl_SFname = new wxTextCtrl( this, ID_TEXTCTRL_SFname, wxT(""), wxDefaultPosition, wxSize(200,-1), 0 );
	m_pTextCtrl_SFname->SetValue(m_potShapeName);

/*
	wxChoice *choice = new wxChoice( this, ID_CHOICE_PK_ColName, wxDefaultPosition, wxSize(200,-1), 0, NULL, 0 );
	wxArrayString ShapeNames;
	CWKSP_Shapes_Manager *pShapes;
	CSG_Shapes *pShape;
	if ( (pShapes = g_pData->Get_Shapes()) != NULL)
	{
		for (int i = 0; i < pShapes->Get_Count(); i++)
		{
			//ShapeNames.Add(pShapes->Get_Shape(i)->Get_Name());
			ShapeNames.Add(pShapes->Get_Shapes(i)->Get_Name());
		}
	}
	for (unsigned int i = 0; i < ShapeNames.size(); i++)
		choice->Append(ShapeNames[i]);
	choice->SetSelection(0);
	item41->Add( choice, 0, wxALIGN_LEFT|wxLEFT, 5 );
*/
	item41->Add( txt_SFname, 0, wxALIGN_CENTER|wxALL, 5 );
	item41->Add( m_pTextCtrl_SFname, 0, wxALIGN_CENTER|wxALL, 5 );
	statBoxSizer_SFname->Add( item41, 0, wxALIGN_CENTER|wxALL, 5 );
	MainBoxSizer->Add( statBoxSizer_SFname, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
	//-------------------------------------------

	//-------------------------------------------
	// Static Box: Primary Key Column
	//-------------------------------------------
    wxStaticBox *item3 = new wxStaticBox( this, -1, wxT("Primary Key Column") );
	item3->SetFont( wxFont( 8, wxSWISS, wxNORMAL, wxBOLD ) );
    wxStaticBoxSizer *item2 = new wxStaticBoxSizer( item3, wxHORIZONTAL );

    wxBoxSizer *item4 = new wxBoxSizer( wxHORIZONTAL );
    wxBoxSizer *item5 = new wxBoxSizer( wxVERTICAL );
   
	m_pRadioButton_select_pk = new wxRadioButton( this, ID_RADIOBUTTON_Select_pk_column, wxT("Select an existing column"), wxDefaultPosition, wxSize(150,-1), 0 );
    m_pRadioButton_select_pk->SetValue( TRUE );
    item4->Add( m_pRadioButton_select_pk, 0, wxALIGN_LEFT|wxRIGHT, 5 );
	
	// CHOICE: PK Column Name ~~~~~~~~~~~~~~~~~~~~~~
    m_pChoice_pk_col = new wxChoice( this, ID_CHOICE_PK_ColName, wxDefaultPosition, wxSize(200,-1), 0, NULL, 0 );
    wxArrayString strs10 = _Get_PK_Column_Names(m_pShapes);
	for (unsigned int i = 0; i < strs10.size(); i++)
		m_pChoice_pk_col->Append(strs10[i]);
	m_pChoice_pk_col->SetSelection(0);
	item4->Add( m_pChoice_pk_col, 0, wxALIGN_LEFT|wxLEFT, 5 );
	//~~~~~~~~~~~~~~~~~~~~~~
	item5->Add(item4, 0, wxALIGN_LEFT|wxALL, 5);

	m_pRadioButton_create_pk = new wxRadioButton( this, ID_RADIOBUTTON_create_pk, wxT("Automatically create a pk column"), wxDefaultPosition, wxSize(200,-1), 0 );
    item5->Add( m_pRadioButton_create_pk, 0, wxALIGN_LEFT|wxALL, 5 );

    item2->Add( item5, 0, wxALIGN_LEFT|wxALL, 5 );
	MainBoxSizer->Add( item2, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

	//----------------------------------------------------------
	// ***** StaticBox: Geometry Columns ***********************
	//----------------------------------------------------------
    wxStaticBox *statBox_GeometryColumns = new wxStaticBox( this, -1, wxT("Geometry Columns") );
	statBox_GeometryColumns->SetFont( wxFont( 8, wxSWISS, wxNORMAL, wxBOLD ) );
    wxStaticBoxSizer *statBoxSizer_GeometryColumns = new wxStaticBoxSizer( statBox_GeometryColumns, wxVERTICAL );

	// box f_table_catalog ~~~~~~~~~~~~~~~~~~~~~~
    wxBoxSizer *box_catalog = new wxBoxSizer( wxHORIZONTAL );

    wxStaticText *txt_f_table_catalog = new wxStaticText( this, ID_TEXT, wxT("f_table_catalog"), wxDefaultPosition, wxSize(150,-1), 0 );
    box_catalog->Add( txt_f_table_catalog, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5 );

    m_pTextCtrl_catalog = new wxTextCtrl( this, ID_TEXTCTRL_catalog, wxT(""), wxDefaultPosition, wxSize(200,-1), 0 );
    box_catalog->Add( m_pTextCtrl_catalog, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5 );

    statBoxSizer_GeometryColumns->Add( box_catalog, 0, wxALIGN_CENTER|wxALL, 5 );
	// ~~~~~~~~~~~~~~~~~~~~~~

	// box f_table_schema ~~~~~~~~~~~~~~~~~~~~~~
    wxBoxSizer *box_schema = new wxBoxSizer( wxHORIZONTAL );

    wxStaticText *item25 = new wxStaticText( this, ID_TEXT, wxT("f_table_schema"), wxDefaultPosition, wxSize(150,-1), 0 );
    box_schema->Add( item25, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5 );

    wxString strs26[] = 
    {
        wxT("public"), 
        wxT("private")
    };
    m_pComboBox_schema = new wxComboBox( this, ID_COMBO_f_schema, wxT(""), wxDefaultPosition, wxSize(200,-1), 2, strs26, wxCB_READONLY );
	m_pComboBox_schema->SetSelection(0);
    box_schema->Add( m_pComboBox_schema, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5 );

    statBoxSizer_GeometryColumns->Add( box_schema, 0, wxALIGN_CENTER|wxALL, 5 );
	// ~~~~~~~~~~~~~~~~~~~~~~

	// box f_geometry_column ~~~~~~~~~~~~~~~~~~~~~~
    wxBoxSizer *box_geometrycolumn = new wxBoxSizer( wxHORIZONTAL );

    wxStaticText *txt_f_table_geocol = new wxStaticText( this, ID_TEXT, wxT("f_geometry_column"), wxDefaultPosition, wxSize(150,-1), 0 );
    box_geometrycolumn->Add( txt_f_table_geocol, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5 );

    m_pTextCtrl_geometrycolumn = new wxTextCtrl( this, ID_TEXTCTRL_geocol, wxT(""), wxDefaultPosition, wxSize(200,-1), 0 );
	m_pTextCtrl_geometrycolumn->SetValue("geom");
    box_geometrycolumn->Add( m_pTextCtrl_geometrycolumn, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5 );

    statBoxSizer_GeometryColumns->Add( box_geometrycolumn, 0, wxALIGN_CENTER|wxLEFT|wxALL, 5 );
	// ~~~~~~~~~~~~~~~~~~~~~~

	// box coord_dimension ~~~~~~~~~~~~~~~~~~~~~~
    wxBoxSizer *box_coord_dimension = new wxBoxSizer( wxHORIZONTAL );

    wxStaticText *stext_cd = new wxStaticText( this, ID_TEXT, wxT("coord_dimension"), wxDefaultPosition, wxSize(150,-1), 0 );
    box_coord_dimension->Add( stext_cd, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5 );

    wxString strs_coorddim[] = 
    {
        wxT("2"), 
    };
    m_pComboBox_coorddimension = new wxComboBox( this, ID_COMBO_f_coorddim, wxT(""), wxDefaultPosition, wxSize(200,-1), 2, strs_coorddim, wxCB_READONLY );
	m_pComboBox_coorddimension->SetSelection(0);
    box_coord_dimension->Add( m_pComboBox_coorddimension, 0, wxALIGN_CENTER|wxLEFT|wxRIGHT, 5 );

    statBoxSizer_GeometryColumns->Add( box_coord_dimension, 0, wxALIGN_CENTER|wxALL, 5 );
	// ~~~~~~~~~~~~~~~~~~~~~~

	// add statBoxSizer_GeometryColumns to main box
    MainBoxSizer->Add( statBoxSizer_GeometryColumns, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
	//----------------------------------------------------------
	// ***** end StaticBox GeometryColumns *********************
	//----------------------------------------------------------

	//----------------------------------------------------------
	// ******** StaticBox: SRID ********************************
	//----------------------------------------------------------
	wxStaticBox *sb_srid= new wxStaticBox( this, -1, wxT("Spatial Reference System") );
	sb_srid->SetFont( wxFont( 8, wxSWISS, wxNORMAL, wxBOLD ) );
    wxStaticBoxSizer *statBoxSizerSRID = new wxStaticBoxSizer( sb_srid, wxHORIZONTAL );

    wxBoxSizer *BSH_srid = new wxBoxSizer( wxHORIZONTAL );
	wxBoxSizer *BSV_srid = new wxBoxSizer( wxVERTICAL );

	wxStaticText *txtSRID = new wxStaticText( this, ID_TEXT, wxT("SRID"), wxDefaultPosition, wxSize(150,-1), 0 );
	BSH_srid->Add(txtSRID, 0, wxALIGN_LEFT|wxALL, 5);

    m_pTextCtrl_SRID = new wxTextCtrl( this, ID_TEXTCTRL_srid, wxT(""), wxDefaultPosition, wxSize(200,-1), 0 );
	BSH_srid->Add(m_pTextCtrl_SRID, 0, wxALIGN_LEFT|wxALL, 5);

	BSV_srid->Add(BSH_srid, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxBoxSizer *BSH_buttons = new wxBoxSizer( wxHORIZONTAL );

    m_pButtonSRID_p = new wxButton( this, ID_ButtonSRID_p, wxT("Projected Coord. Systems"), wxDefaultPosition, wxSize(150,-1), 0 );
	BSH_buttons->Add( m_pButtonSRID_p, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

	m_pButtonSRID_g = new wxButton( this, ID_ButtonSRID_g, wxT("Geographic Coord. Systems"), wxDefaultPosition, wxSize(150,-1), 0 );
	BSH_buttons->Add( m_pButtonSRID_g, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
	
	BSV_srid->Add( BSH_buttons, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

	statBoxSizerSRID->Add(BSV_srid, 0, wxALIGN_LEFT|wxALL, 5);

	MainBoxSizer->Add(statBoxSizerSRID, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

	// ***** end StaticBox SRID ********************************
	//----------------------------------------------------------

	//-------------------------------------------
	// Button box
	//-------------------------------------------
    wxBoxSizer *item19 = new wxBoxSizer( wxHORIZONTAL );

    wxButton *item20 = new wxButton( this, wxID_OK, wxT("OK"), wxDefaultPosition, wxDefaultSize, 0 );
    item19->Add( item20, 0, wxALIGN_CENTER|wxALL, 5 );

    wxButton *item21 = new wxButton( this, wxID_CANCEL, wxT("Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
    item19->Add( item21, 0, wxALIGN_CENTER|wxALL, 5 );

    MainBoxSizer->Add( item19, 0, wxALIGN_CENTER|wxALL, 5 );
	//-------------------------------------------

	//-------------------------------------------
	this->SetSizer( MainBoxSizer );
	MainBoxSizer->Fit(this);
    MainBoxSizer->SetSizeHints( this );
	//-------------------------------------------
}
//---------------------------------------------------------------------

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

//---------------------------------------------------------------------
wxArrayString CSimpleFeature_export_dlg::_Get_PK_Column_Names(CSG_Shapes *pShapes)
{
	// Returns potential column names of the current SimpleFeature
	// to use as Primary Key.
	// Only field types 'Int' or 'Long' are accepted and listed !!!
	wxArrayString ColNames;

	if (pShapes != NULL)
	{
		for (int i = 0; i < pShapes->Get_Table().Get_Field_Count(); i++)
		{
			if (pShapes->Get_Table().Get_Field_Type(i) == TABLE_FIELDTYPE_Int ||
				pShapes->Get_Table().Get_Field_Type(i) == TABLE_FIELDTYPE_Long)
			{
				ColNames.Add(pShapes->Get_Table().Get_Field_Name(i));
			}
		}
		return(ColNames);
	} else {
		return(ColNames.Add("_NULL"));
	}
}

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

///////////////////////////////////////////////////////////////////////
//
//	EVENT TABLE FUNCTIONS
//
///////////////////////////////////////////////////////////////////////

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

void CSimpleFeature_export_dlg::On_RadioButtonSelected_pk(wxCommandEvent &event)
{
	if (m_pRadioButton_create_pk->GetValue())
	{
		//m_pTextCtrl_pk_colname->Enable();
		m_pChoice_pk_col->Disable();
	}
	if (m_pRadioButton_select_pk->GetValue())
	{
		//m_pTextCtrl_pk_colname->Disable();
		m_pChoice_pk_col->Enable();
	}
	event.Skip();
}
//---------------------------------------------------------------------

void CSimpleFeature_export_dlg::On_ButtonSRID_p(wxCommandEvent& event)
{
	CSimpleFeature_export_dlg_srid *pSRID = new CSimpleFeature_export_dlg_srid(this, -1, "Select SRID", 0);
	if (pSRID->ShowModal() == wxID_OK)
	{	
		m_pTextCtrl_SRID->SetValue(convert_sl::Int2String(pSRID->Get_SRID()).c_str());
	}
}
//---------------------------------------------------------------------

void CSimpleFeature_export_dlg::On_ButtonSRID_g(wxCommandEvent& event)
{
	CSimpleFeature_export_dlg_srid *pSRID = new CSimpleFeature_export_dlg_srid(this, -1, "Select SRID", 1);
	if (pSRID->ShowModal() == wxID_OK)
	{	
		m_pTextCtrl_SRID->SetValue(convert_sl::Int2String(pSRID->Get_SRID()).c_str());
	}
}