///////////////////////////////////////////////////////////
// Author:			Stefan Liersch
// Contact:			stefan.liersch@googlemail.com,
//					stefan.liersch@ufz.de
//
// Date:			2008-03-25
// last modified:	2008-03-25
//
//---------------------------------------------------------
// DESCRIPTION
//---------------------------------------------------------
//
//---------------------------------------------------------
// ToDo
//---------------------------------------------------------
//	- Allthough the period (a,b) is stored in the database
//		attribute table, the value will not be displayed
//		in the sf/saga attribute table. Maybe that has to do
//		with type character, maybe not...
//	- tho load data dialog is not yet save. if for instance data
//		of the first feature are missing for a certain year, the
//		attribute table is filled in not correctly. hence it is
//		required to check the fid in the db and to input the data 
//		to the SAGA attribute table according to the fid.
///////////////////////////////////////////////////////////

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

#include "libpq-fe.h"

#include "pg_soil_salinity_load_data_dlg.h"

//#include "saga_gui/wksp_shapes_manager.h"
#include "saga_gui/wksp_simplefeature_manager.h"
#include "saga_gui/wksp_layer.h"
#include "saga_gui/wksp_data_manager.h" // g_pData
#include "saga_gui/wksp_table.h"
#include "saga_gui/wksp_table_manager.h"
#include "saga_gui/SAGA_Frame.h"
#include "saga_gui/helper.h"			// using function MSG_General_Add()
#define MSG_ADD(s)	MSG_General_Add(s, true, true);

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

BEGIN_EVENT_TABLE(CSoilSalinityLoadDataDlg, wxDialog)
	EVT_BUTTON(ID_SSLD_LOAD_DATA,		_On_Button_Load)
END_EVENT_TABLE()
//---------------------------------------------------------------------

CSoilSalinityLoadDataDlg::CSoilSalinityLoadDataDlg()
{
}
//---------------------------------------------------------------------
CSoilSalinityLoadDataDlg::CSoilSalinityLoadDataDlg(CSG_SimpleFeature* pSimpleFeature, wxWindow *parent, wxWindowID id, const wxString &title,bool b)
	: wxDialog(parent, id, title,
	  wxPoint(200,50),//wxDefaultPosition,
	  wxDefaultSize,
	  wxDEFAULT_DIALOG_STYLE),
	  CSoilSalinityDlgBase(pSimpleFeature)
{
	m_pSimpleFeature = pSimpleFeature;
}
//---------------------------------------------------------------------

CSoilSalinityLoadDataDlg::CSoilSalinityLoadDataDlg(CSG_SimpleFeature* pSimpleFeature, wxWindow *parent, wxWindowID id, const wxString &title)
	: wxDialog(parent, id, title,
	  wxPoint(200,50),//wxDefaultPosition,
	  wxDefaultSize,
	  wxDEFAULT_DIALOG_STYLE),
	  CSoilSalinityDlgBase(pSimpleFeature)
{
	m_pSimpleFeature = pSimpleFeature;
	if (g_pSAGA_Frame->db->CheckAccessibility(_Get_AttributeTableName().c_str()) ) {
		
		_CreateDialog(pSimpleFeature);
	}
}
//---------------------------------------------------------------------

CSoilSalinityLoadDataDlg::~CSoilSalinityLoadDataDlg()
{
	_Delete_Controls();
}

///////////////////////////////////////////////////////////////////////
//
//	EVENT HANDLER FUNCTIONS
//
///////////////////////////////////////////////////////////////////////

//---------------------------------------------------------------------
void CSoilSalinityLoadDataDlg::_On_Button_Load(wxCommandEvent &event)
{
	if ( Get_Active_Layer() ) { // CWKSP_Layer
		CSG_Data_Object* m_pObject = Get_Active_Layer()->Get_Object();
		// Check, if a SimpleFeature is active
		if (m_pObject->Get_ObjectType() == DATAOBJECT_TYPE_SimpleFeature &&
			m_pObject->asSimpleFeature()->Get_SF_Category() == SF_CATEGORY_SoilSalinityMap) {

			m_pSQLTable = new Csqltable(m_pSimpleFeature->Get_FeatureName());

			if ( g_pSAGA_Frame->db->Get_QueryResult(_Get_Query().c_str(), m_pSQLTable) ) {
				_Modify_SFTable(m_pSQLTable, 8);
			}
			delete m_pSQLTable;

		} else {
			SG_UI_Dlg_Message("Please select the soil salinity map!","Error: Wrong feature selected!");
		}		
	} else {
		SG_UI_Dlg_Message("Please select a SimpleFeature Layer","Error: Wrong feature selected!");
	}

	event.Skip();
}
//---------------------------------------------------------------------

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

CSG_String CSoilSalinityLoadDataDlg::_Get_Query()
{
	CSG_String sql = "SELECT fid, yr, mnth, salinity, salinity_v, ms_low, ms_medium, ms_high, plant FROM ";
	sql.Append(_Get_AttributeTableName());
	sql.Append(" WHERE yr = ");
	sql.Append(m_pComboYear->GetValue().c_str());
	sql.Append(" AND mnth = '");
	sql.Append(m_pComboMonth->GetValue().c_str());
	sql.Append("'");
	sql.Append(" ORDER BY fid");
	return(sql);
}
//---------------------------------------------------------------------

void CSoilSalinityLoadDataDlg::_Modify_SFTable(Csqltable* pSQLTable, int nModify)
{
	CWKSP_SimpleFeature*	pSimpleFeature = _Get_WKSP_SimpleFeature(m_pSimpleFeature);
	CWKSP_Table*			pWKSPTable = pSimpleFeature->Get_Table();
	CSG_Table*				pTable = pWKSPTable->Get_Table();
	
	_EmptyAttributeTable(pTable, nModify);
	CSG_Table_Record* pRecord = NULL;
	for (int row = 0; row < pSQLTable->Get_nrows(); row++) {
		//pRecord = pTable->Get_Record(row);
		pRecord = pTable->Get_Record(convert_sl::StringToInt(pSQLTable->GetValue(0,row))-1);
		for (int col = 1; col < nModify + 1; col++) {
			pRecord->Set_Value(col,pSQLTable->GetValue(col,row).c_str());
		}
	}

	pWKSPTable->Update_Views();
	pSimpleFeature->Update_Views(true);
}
//---------------------------------------------------------------------

void CSoilSalinityLoadDataDlg::_EmptyAttributeTable(CSG_Table* pTable, int nModify)
{
	CSG_Table_Record* pRecord = NULL;
	for (int row = 0; row < pTable->Get_Record_Count(); row++) {
		pRecord = pTable->Get_Record(row);
		for (int col = 1; col < nModify + 1 ; col++) {
			pRecord->Set_Value(col,"0");
		}
	}
}

///////////////////////////////////////////////////////////////////////
//
//	DIALOG
//
///////////////////////////////////////////////////////////////////////
void CSoilSalinityLoadDataDlg::_CreateDialog(CSG_SimpleFeature* pSimpleFeature)
{
    wxBoxSizer *mainBox = new wxBoxSizer( wxVERTICAL );
	wxStaticBox *pStatBoxYear = new wxStaticBox( this, wxID_ANY, wxT("Date") );
	wxStaticBoxSizer* pStatBoxSizerYear = new wxStaticBoxSizer( pStatBoxYear, wxHORIZONTAL );
	wxBoxSizer *ButtonBox = new wxBoxSizer( wxHORIZONTAL );

	// Year
	m_pComboYear = new wxComboBox( this, ID_SSLD_COMBO_YEAR, wxT(""), wxDefaultPosition, wxSize(80,-1), 0, NULL, wxCB_SORT|wxCB_READONLY );
	wxArrayString as = _Get_Years(_Get_SQL_Get_Years());
	for (unsigned int i = 0; i < as.size(); i++) {
		m_pComboYear->Append(as[i]);
	}
	m_pComboYear->SetSelection(0);
	pStatBoxSizerYear->Add( m_pComboYear, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

	// Month
	m_pComboMonth = new wxComboBox( this, ID_SSLD_COMBO_MONTH, wxEmptyString, wxDefaultPosition, wxSize(45,-1), 0, NULL, wxCB_DROPDOWN|wxCB_READONLY );
	wxArrayString amon = _Get_Month_Array();
	for (unsigned int i = 0; i < amon.size(); i++) {
		m_pComboMonth->Append(amon[i]);
	}
	m_pComboMonth->SetSelection(10);
	pStatBoxSizerYear->Add( m_pComboMonth, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

	// Buttons
	m_pButton_LoadData = new wxButton( this, ID_SSLD_LOAD_DATA, wxT("Load"), wxDefaultPosition, wxSize(75,-1), 0 );
	wxButton* pButtonCancel = new wxButton( this, wxID_CANCEL, wxT("Cancel"), wxDefaultPosition, wxSize(75,-1), 0 );
	ButtonBox->Add( m_pButton_LoadData, 0, wxALIGN_CENTER|wxALL, 5 );
    ButtonBox->Add( pButtonCancel, 0, wxALIGN_CENTER|wxALL, 5 );

	// add features to mainBox
	mainBox->Add(pStatBoxSizerYear, 0, wxALIGN_LEFT|wxALL, 5 );
	mainBox->Add(ButtonBox, 0, wxALIGN_CENTER|wxALL, 5);

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

void CSoilSalinityLoadDataDlg::_Delete_Controls()
{
	delete m_pComboYear;
	delete m_pComboMonth;
}

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

CSG_String CSoilSalinityLoadDataDlg::_Get_SQL_Get_Years()
{
	CSG_String sql = "SELECT DISTINCT yr FROM ";
	sql.Append( _Get_AttributeTableName() );
	return(sql);
}

wxArrayString CSoilSalinityLoadDataDlg::_Get_Years(CSG_String sql)
{
	wxArrayString astr = NULL;
	wxString error ="";
	//CSG_String sql = "SELECT DISTINCT year FROM ";
	//sql.Append( _Get_AttributeTableName() );

	PGresult* res = g_pSAGA_Frame->db->ExecSQL_wx2(sql.c_str());
	if ( g_pSAGA_Frame->db->ExecSQL_wx1(res,sql.c_str(),error)  ){
		//astr.resize( PQntuples(res) );
		for (int i = 0; i < PQntuples(res); i++) {
			astr.Add(PQgetvalue(res,i,0));
		}

		PQclear(res);
		return(astr);
	} else {
		PQclear(res);
		MSG_ADD(error.c_str());
		//astr.resize(0);
		return(astr);
	}
}
//---------------------------------------------------------------------
