///////////////////////////////////////////////////////////
// File:			pg_soil_salinity_compare_dlg.cpp
//
// Author:			Stefan Liersch
// Contact:			stefan.liersch@googlemail.com,
//					stefan.liersch@ufz.de
//
// Date:			2008-09-30
// last modified:	2008-09-30
//
//---------------------------------------------------------
// DESCRIPTION
//---------------------------------------------------------
//
//---------------------------------------------------------
// ToDo
//---------------------------------------------------------
//	- 
///////////////////////////////////////////////////////////

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

#include "pg_soil_salinity_compare_dlg.h"
#include "saga_gui/wksp_table.h"
#include "saga_gui/active_parameters.h"
#include "saga_gui/wksp_layer_classify.h"
#include <fstream>
//---------------------------------------------------------------------

BEGIN_EVENT_TABLE(CSoilSalinityCompareDlg, wxDialog)
	EVT_BUTTON(ID_CMD_SSC_BUTTON_COMPARE,	_On_Button_Compare)
END_EVENT_TABLE()
//---------------------------------------------------------------------

CSoilSalinityCompareDlg::CSoilSalinityCompareDlg(CSoilSalinityMap* pSSMap, bool bCreate, wxWindow *parent, wxWindowID id, const wxString &title)
	: wxDialog(parent, id, title,
	  wxDefaultPosition, wxDefaultSize,
	  wxDEFAULT_DIALOG_STYLE)
{
	if ( bCreate ) {
		// in order to compare maps the original map will be copied to the SAGA workspace
		// therefore, a new object is created and loaded from the database
		// maybe this could be improved here.
		CSG_Data_Object*	pObject;
		pObject = new CSG_SimpleFeature(g_pSAGA_Frame->db->GetConn(), pSSMap->Get_MapName().c_str(),
			g_pSAGA_Frame->db->_Get_GeometryColumnName(pSSMap->Get_MapName().c_str()));

		m_pSSMap = new CSoilSalinityMap(pObject->asSimpleFeature());

		// modify SAGA attriute table
		m_pTable = m_pSSMap->Get_SimpleFeature()->Get_Table().asTable();
		m_pTable->Add_Field("Diff",TABLE_FIELDTYPE_Float,1);

		// create a new layer
		m_pTable->Set_Name("ssm_comparison");
		m_pSSMap->Get_SimpleFeature()->Set_Name("ssm_comparison");

		g_pData->Add(m_pSSMap->Get_SimpleFeature()->asSimpleFeature());
		g_pData->Show(m_pSSMap->Get_SimpleFeature()->asSimpleFeature());
		g_pData->Update_Views(m_pSSMap->Get_SimpleFeature());

		// comparison map as active layer
		g_pACTIVE->Set_Active( g_pData->Get_SimpleFeatures()->Get_Shapes(pObject->asSimpleFeature()) );

	} else { // layer exists
		m_pSSMap = pSSMap;
		m_pTable = m_pSSMap->Get_SimpleFeature()->Get_Table().asTable();
	}

	// Set maps category to SoilSalinityCompare
	m_pSSMap->Get_SimpleFeature()->Set_Category(SF_CATEGORY_SoilSalinityCompare);

	_Get_MinMaxYears(m_minYear, m_maxYear);
	m_nYears = m_maxYear - m_minYear + 1;



	// modify CACTIVE / LEGEND
	CWKSP_Layer* pLayer;
	pLayer = Get_Active_Layer();
	CSG_Parameters* pParameters = pLayer->Get_Parameters();

	pParameters->Get_Parameter("COLORS_TYPE")->Set_Value(1); // Set to lookup table

	pLayer->Get_Classifier()->Initialise_SSCM(pLayer, pParameters->Get_Parameter("LUT")->asTable(), pParameters->Get_Parameter("METRIC_COLORS")->asColors());

	pLayer->DataObject_Changed();
	
//	CWKSP_SimpleFeature* pWKSPSF = g_pData->Get_SimpleFeatures()->Get_Shapes(m_pSSMap->Get_SimpleFeature());

	//pWKSPSF->m_Parameters("COLORS_ATTRIB")->Set_Value(1);
	//pParameters = pLayer->Get_Object()->asShapes()->Get_Parameter();

//	pParameters->Get_Parameter("COLORS_ATTRIB")->Set_Value(2);
	


	//CWKSP_Layer_Classify	*m_pClassify;
	//CSG_Table* pLUT = new CSG_Table(); // = pLayer->Get_Classifier()->Get_LUT();
	//pLUT->Add_Field(LNG("COLORe")		, TABLE_FIELDTYPE_Color);
	//pLUT->Add_Field(LNG("NAMEe")			, TABLE_FIELDTYPE_String);
	//pLUT->Add_Field(LNG("DESCRIPTIONe")	, TABLE_FIELDTYPE_String);
	//pLUT->Add_Field(LNG("MINIMUMe")		, TABLE_FIELDTYPE_Double);
	//pLUT->Add_Field(LNG("MAXIMUMe")		, TABLE_FIELDTYPE_Double);
	//
	//CSG_Table_Record	*pRecord;

	//pRecord	= pLUT->Add_Record();
	//pRecord->Set_Value(0		, SG_GET_RGB(100, 100, 100));
	//pRecord->Set_Value(1, LNG("Classe 4"));
	//pRecord->Set_Value(2, LNG("Sslköjf Class"));
	//pRecord->Set_Value(3, 0.0);
	//pRecord->Set_Value(4, 1.0);

	//pRecord	= pLUT->Add_Record();
	//pRecord->Set_Value(0		, SG_GET_RGB(255, 60, 90));
	//pRecord->Set_Value(1, LNG("Classe 2"));
	//pRecord->Set_Value(2, LNG("Second Class"));
	//pRecord->Set_Value(3, 1.0);
	//pRecord->Set_Value(4, 2.0);

	//pLayer->Get_Classifier()->Set_LUT(pLUT);
	////pLayer->On_Create_Parameters();
	//pLayer->DataObject_Changed();


//	CACTIVE_Parameters* pP = g_pACTIVE->Get_Parameters();
	//pP->Update_Parameters(pParameters,false);
	//pLayer->DataObject_Changed();


	_CreateDialog();

}

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

CSG_String CSoilSalinityCompareDlg::_Get_Select_Year(int year, CSG_String month)
{
	std::ostringstream sql;

	sql << "SELECT DISTINCT " << m_pSSMap->Get_AttrFieldName()->Get_FieldName(1) << ", "; // fid
	sql << m_pSSMap->Get_AttrFieldName()->Get_FieldName(5); // salinity_v
	sql << " FROM " << m_pSSMap->Get_AttributeTableName();
	sql << " WHERE " << m_pSSMap->Get_AttrFieldName()->Get_FieldName(2) << " = " << year;
	sql << " AND " << m_pSSMap->Get_AttrFieldName()->Get_FieldName(3) << " = '" << month << "'";
	sql << " ORDER BY " << m_pSSMap->Get_AttrFieldName()->Get_FieldName(1); // fid

	return(sql.str().c_str());
}
//---------------------------------------------------------------------

bool CSoilSalinityCompareDlg::_Get_Salinity(CSG_String sql, vector_d &salinity)
{
	unsigned int index = 0;
	PGresult*	res = g_pSAGA_Frame->db->ExecSQL_wx2(sql.c_str());
	if (PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		PQclear(res);
		return(false);
	} else {
		int nrows = PQntuples(res);
		if ( nrows == m_pSSMap->Get_SimpleFeature()->Get_nFeatures() ) {
			for (int row = 0; row < nrows; row++) {
				salinity[row] = convert_sl::StringToDouble( PQgetvalue(res,row,1) );
			}
		} else {
			for ( int row = 0; row < nrows; row++) {
				index = convert_sl::StringToInt( PQgetvalue(res,row,0) ) - 1;
				salinity[index] = convert_sl::StringToDouble( PQgetvalue(res,row,1) );
			}
		}
		PQclear(res);
		return(true);
	}
}
//---------------------------------------------------------------------

bool CSoilSalinityCompareDlg::_Get_MinMaxYears(int& min, int& max)
{
	if ( g_pSAGA_Frame->db->GetMinMaxValue(m_pSSMap->Get_AttributeTableName().c_str(),m_pSSMap->Get_AttrFieldName()->Get_FieldName(2).c_str(),min,max) )
		return(true);
	else
		return(false);
}
//---------------------------------------------------------------------

void CSoilSalinityCompareDlg::_On_Button_Compare(wxCommandEvent& event)
{
	int			year1 = convert_sl::StringToInt( m_pCombo_Year1->GetValue().c_str() );
	int			year2 = convert_sl::StringToInt( m_pCombo_Year2->GetValue().c_str() );
	CSG_String	month1 = m_pCombo_Month1->GetValue().c_str();
	CSG_String	month2 = m_pCombo_Month1->GetValue().c_str();

	// salinity vectors (year1 and year2)
	vector_d	salinity1;
	vector_d	salinity2;
	unsigned int	nvals = m_pSSMap->Get_SimpleFeature()->Get_nFeatures();
	salinity1.resize(nvals);
	salinity2.resize(nvals);
	m_diff.resize(nvals);
	for (unsigned int i = 0; i < nvals; i++) {
		salinity1[i] = 0.0;
		salinity2[i] = 0.0;
		m_diff[i]	 = 0.0;
	}

	std::ofstream f("_compare.txt");

	// dialog select year

	// select salinity_v values year 1
	_Get_Salinity(_Get_Select_Year(year1, month1), salinity1);
	for (unsigned int i = 0; i < salinity1.size(); i++) {
		f << i << ": " << salinity1[i] << std::endl;
	}

	// select salinity_v values year 2
	_Get_Salinity(_Get_Select_Year(year2, month2), salinity2);
	for (unsigned int i = 0; i < salinity2.size(); i++) {
		f << i << ": " << salinity2[i] << std::endl;
	}

	// calculate difference between year 1 and year 2
	for (unsigned int i = 0; i < m_diff.size(); i++) {
		m_diff[i] = salinity1[i] - salinity2[i];
		f << i << "diff: " << m_diff[i] << std::endl;
	}

	_Write_DifferenceToTable();

	// saga workspace attribute table modifizieren
	// delete all column except FID
	// create new column 'dif'

	// update view
}
//---------------------------------------------------------------------

void CSoilSalinityCompareDlg::_Write_DifferenceToTable()
{
	//CSG_Table*	pTable;
	//pTable = m_pSSMap->Get_SimpleFeature()->Get_Table().asTable();

	CWKSP_SimpleFeature*	pWKSPSimpleFeature = m_DLG_Base._Get_WKSP_SimpleFeature(m_pSSMap->Get_SimpleFeature());
	CWKSP_Table*			pWKSPTable = pWKSPSimpleFeature->Get_Table();

	for (unsigned int i = 0; i < m_pSSMap->Get_SimpleFeature()->Get_nFeatures(); i++) {
		m_pTable->Set_Value(i,1,m_diff[i]);
	}

	pWKSPTable->Update_Views();
	pWKSPSimpleFeature->Update_Views(true);

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

void CSoilSalinityCompareDlg::_CreateDialog()
{
	wxBoxSizer* bMainSizer;
	bMainSizer = new wxBoxSizer( wxVERTICAL );
	
	wxStaticBoxSizer* bSizerBegin;
	bSizerBegin = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxT("First time step") ), wxHORIZONTAL );
	
	wxStaticText* m_staticText36 = new wxStaticText( this, wxID_ANY, wxT("Year"), wxDefaultPosition, wxDefaultSize, 0 );
	bSizerBegin->Add( m_staticText36, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
	
	m_pCombo_Year1 = new wxComboBox( this, ID_CMD_SSC_COMBO_YEAR1, wxEmptyString, wxDefaultPosition, wxSize( 60,-1 ), 0, NULL, wxCB_DROPDOWN|wxCB_READONLY ); 
	for (int year = m_minYear; year < m_maxYear+1; year++) {
		m_pCombo_Year1->Append(convert_sl::Int2String(year).c_str());
	}
	m_pCombo_Year1->SetSelection(0);
	bSizerBegin->Add( m_pCombo_Year1, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
	
	wxStaticText* m_staticText37 = new wxStaticText( this, wxID_ANY, wxT("Month"), wxDefaultPosition, wxDefaultSize, 0 );
	bSizerBegin->Add( m_staticText37, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
	
	m_pCombo_Month1 = new wxComboBox( this, ID_CMD_SSC_COMBO_MONTH1, wxEmptyString, wxDefaultPosition, wxSize( 60,-1 ), 0, NULL, wxCB_DROPDOWN|wxCB_READONLY ); 
	wxArrayString m1 = m_DLG_Base._Get_Month_Array();
	for (unsigned int i = 0; i < m1.size(); i++) {
		m_pCombo_Month1->Append(m1[i]);
	}
	m_pCombo_Month1->SetSelection(10);
	bSizerBegin->Add( m_pCombo_Month1, 0, wxALL, 5 );
	
	bMainSizer->Add( bSizerBegin, 0, wxALL, 5 );
	
	wxStaticBoxSizer* bSizerEnd;
	bSizerEnd = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxT("Second time step") ), wxHORIZONTAL );
	
	wxStaticText* m_staticText361 = new wxStaticText( this, wxID_ANY, wxT("Year"), wxDefaultPosition, wxDefaultSize, 0 );
	m_staticText361->Wrap( -1 );
	bSizerEnd->Add( m_staticText361, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
	
	m_pCombo_Year2 = new wxComboBox( this, ID_CMD_SSC_COMBO_YEAR2, wxEmptyString, wxDefaultPosition, wxSize( 60,-1 ), 0, NULL, wxCB_DROPDOWN|wxCB_READONLY ); 
	for (int year = m_minYear; year < m_maxYear+1; year++) {
		m_pCombo_Year2->Append(convert_sl::Int2String(year).c_str());
	}
	m_pCombo_Year2->SetSelection(m_nYears-1);
	bSizerEnd->Add( m_pCombo_Year2, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
	
	wxStaticText* m_staticText371 = new wxStaticText( this, wxID_ANY, wxT("Month"), wxDefaultPosition, wxDefaultSize, 0 );
	m_staticText371->Wrap( -1 );
	bSizerEnd->Add( m_staticText371, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
	
	m_pCombo_Month2 = new wxComboBox( this, ID_CMD_SSC_COMBO_MONTH2, wxEmptyString, wxDefaultPosition, wxSize( 60,-1 ), 0, NULL, wxCB_DROPDOWN|wxCB_READONLY ); 
	wxArrayString m2 = m_DLG_Base._Get_Month_Array();
	for (unsigned int i = 0; i < m2.size(); i++) {
		m_pCombo_Month2->Append(m2[i]);
	}
	m_pCombo_Month2->SetSelection(10);
	bSizerEnd->Add( m_pCombo_Month2, 0, wxALL, 5 );
	
	bMainSizer->Add( bSizerEnd, 0, wxALL, 5 );
	
	wxBoxSizer* bSizer26;
	bSizer26 = new wxBoxSizer( wxHORIZONTAL );
	
	m_pButtonCompare = new wxButton( this, ID_CMD_SSC_BUTTON_COMPARE, wxT("Compare"), wxDefaultPosition, wxSize( 100,-1 ), 0 );
	bSizer26->Add( m_pButtonCompare, 0, wxALL, 5 );
	
	m_pButtonCancel = new wxButton( this, wxID_CANCEL, wxT("Cancel"), wxDefaultPosition, wxSize( 100,-1 ), 0 );
	bSizer26->Add( m_pButtonCancel, 0, wxALL, 5 );
	
	bMainSizer->Add( bSizer26, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5 );
	
	this->SetSizer( bMainSizer );
	this->Layout();
	bMainSizer->Fit( this );
}
//---------------------------------------------------------------------
