///////////////////////////////////////////////////////////
// File:			pg_dlg_average_gauges.cpp
//
// Author:			Stefan Liersch
// Contact:			stefan.liersch@googlemail.com,
//					stefan.liersch@ufz.de
//
// Date:			2007-08-30
// last modified:	2007-09-02
//
//---------------------------------------------------------
// DESCRIPTION
//---------------------------------------------------------
// DIALOG for
// Calculating an average time series of selected gauges
//
//---------------------------------------------------------
// RESTRICTION
// The table '_dates19002078' must exist
// This table is necessary to make a LEFT JOIN on the dates
//
//---------------------------------------------------------
// ToDo
//---------------------------------------------------------
// 
// - in ChoiceBox 'm_pChoiceGauges' werden nicht immer die
//	richtigen Stationsnamen angezeigt! ? auf den ersten Blick
//	weiß ich nicht woran es liegen könnte!
///////////////////////////////////////////////////////////

//---------------------------------------------------------------------
#include "pgsql/pg_dlg_average_gauges.h"
#include "hydrology/rr_dlg_preproc.h"
#include "hydrology/rr_preprocessing.h"
#include "pgsql/pg_date_dlg.h"

// SAGA Header
#include "saga_gui/saga_frame.h"		// location of class Cpgdatabase
										// using global *g_pSAGA_Frame pointer
#include "saga_gui/wksp_data_manager.h" // g_pData
#include "saga_gui/wksp_simplefeature_manager.h"
#include "saga_gui/wksp_layer.h"
#include "saga_gui/res_images.h"
#include "saga_gui/res_commands.h"

#include <fstream> // for test output only

#include "saga_gui/helper.h"			// using function MSG_General_Add()
#define MSG_ADD(s)	MSG_General_Add(s, true, true);

//---------------------------------------------------------------------
// IDs defined in 'res_commands.h'
BEGIN_EVENT_TABLE(C_dlg_ave_gauges, wxDialog)
	EVT_BUTTON(ID_BUTTON_SELECT_GAUGES,		_On_Button_Select_Gauges)
	EVT_BUTTON(ID_BUTTON_GET_TS,			_On_Button_GetTimeSeries)
	EVT_BUTTON(wxID_OK,						_On_Button_OK)
	EVT_BUTTON(ID_BUTTON_PG_WEIGHT,			_On_Button_Weight)
END_EVENT_TABLE()

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

//---------------------------------------------------------------------
// CONSTRUCTORS
C_dlg_ave_gauges::C_dlg_ave_gauges(wxWindow *parent, wxWindowID id, const wxString &title)
								   : wxDialog(parent, id, title,
									 wxDefaultPosition, wxDefaultSize,
									 wxDEFAULT_DIALOG_STYLE)
{
	_CreateDlg();
	_ZeroAll();
}
//---------------------------------------------------------------------

C_dlg_ave_gauges::C_dlg_ave_gauges()
{
	_ZeroAll();
}
//---------------------------------------------------------------------

// DESTRUCTOR
C_dlg_ave_gauges::~C_dlg_ave_gauges()
{
	delete m_pLUT;
	delete[] m_pTS;
	this->Destroy();
}

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

///////////////////////////////////////////////////////////
//
//	DIALOG design
//
///////////////////////////////////////////////////////////

void C_dlg_ave_gauges::_CreateDlg()
{
	wxBoxSizer *mainBoxSizer = new wxBoxSizer( wxVERTICAL );

	// BOX GAUGES -----------------------------------------
	wxStaticBox *statbox_gauges = new wxStaticBox( this, -1, wxT("Time Series") );
	statbox_gauges->SetFont( wxFont( 8, wxSWISS, wxNORMAL, wxBOLD ) );
    wxStaticBoxSizer *StatBoxGauges = new wxStaticBoxSizer( statbox_gauges, wxHORIZONTAL );

	m_pChoiceGauges = new wxChoice(this, ID_CHOICE_GAUGES, wxDefaultPosition, wxSize(150,-1), NULL, 0);
	m_pButSelectGauges = new wxButton(this, ID_BUTTON_SELECT_GAUGES, wxT("Get Gauge(s) Data"), wxDefaultPosition, wxSize(200,-1), 0);

	m_pButWeight = new wxBitmapButton( this, ID_BUTTON_PG_WEIGHT, IMG_Get_Bitmap(ID_IMG_PG_WEIGHT), wxDefaultPosition, wxSize(28,28), wxBU_AUTODRAW );
	m_pButWeight->Disable();
	m_pButWeight->SetToolTip("Define weighting factors");

	StatBoxGauges->Add(m_pChoiceGauges, 0, wxALIGN_LEFT|wxALL, 5);
	StatBoxGauges->Add(m_pButSelectGauges, 0, wxALIGN_LEFT|wxALL, 5);
	StatBoxGauges->Add(m_pButWeight, 0, wxALIGN_CENTER|wxALL, 5);
	// BOX GAUGES -----------------------------------------

	// BUTTON BOX ------------------------------------------
    wxBoxSizer *ButBoxSizer = new wxBoxSizer( wxHORIZONTAL );
    m_pButOK = new wxButton( this, wxID_OK, wxT("Create Time Series"), wxDefaultPosition, wxDefaultSize, 0 );
	m_pButOK->Disable();
    ButBoxSizer->Add( m_pButOK, 0, wxALIGN_CENTER|wxALL, 5 );
    wxButton *ButCancel = new wxButton( this, wxID_CANCEL, wxT("Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
    ButBoxSizer->Add( ButCancel, 0, wxALIGN_CENTER|wxALL, 5 );
	m_pButGetTimeSeries = new wxButton( this, ID_BUTTON_GET_TS, wxT("Analyze Time Series"), wxDefaultPosition, wxDefaultSize, 0 );
	ButBoxSizer->Add( m_pButGetTimeSeries, 0, wxALIGN_CENTER|wxALL, 5 );
	// BUTTON BOX ------------------------------------------

	// Add items to mainBoxSizer
	mainBoxSizer->Add(StatBoxGauges,0,wxALIGN_LEFT|wxALL,5);
	mainBoxSizer->Add(ButBoxSizer, 0, wxALIGN_CENTER|wxALL, 5 );

    this->SetSizer( mainBoxSizer );
	mainBoxSizer->Fit(this);
    mainBoxSizer->SetSizeHints( this );

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

void C_dlg_ave_gauges::_ZeroAll()
{
	m_pLUT		= NULL;
	m_pTS		= NULL;
}
//---------------------------------------------------------------------

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

void C_dlg_ave_gauges::_On_Button_GetTimeSeries(wxCommandEvent &event)
{
	_Create_TimeSeries();
}
//---------------------------------------------------------------------

void C_dlg_ave_gauges::_On_Button_Weight(wxCommandEvent &event)
{
	m_RRdlg.Create_DLG_Weight(m_pTS, m_pChoiceGauges);
}
//---------------------------------------------------------------------

void C_dlg_ave_gauges::_On_Button_OK(wxCommandEvent &event)
{
	CRR_preprocessing	*rr = new CRR_preprocessing(m_pTS,m_nIDs,
													m_pTS[0].Get_Date_Begin(), m_pTS[0].Get_Date_End());

	//this->Destroy();
	m_pButOK->Disable();
	delete rr;
}
//---------------------------------------------------------------------

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

void C_dlg_ave_gauges::_On_Button_Select_Gauges(wxCommandEvent &event)
{
	class CWKSP_SimpleFeature	*pWKSP_SimpleFeature = NULL;
	CSG_SimpleFeature	*pSimpleFeature = NULL;
	wxString			PK_ColumnName = "";
	int					PK_ColumnNumber = 0;
	wxString			LUT_Name = "";
	int					*ID;

	pSimpleFeature = m_RRdlg.Get_ActiveFeature();

	if ( pSimpleFeature != NULL )
		pWKSP_SimpleFeature = m_RRdlg.Get_ActiveWKSP_Shapes(pSimpleFeature);

	if ( pWKSP_SimpleFeature != NULL )
		LUT_Name = m_RRdlg.Get_LUT_Name(pWKSP_SimpleFeature, PK_ColumnNumber, PK_ColumnName);

	if ( LUT_Name != "" )
	{
		if (pSimpleFeature->Get_Selection_Count() > 0)
		{
			ID = new int[pSimpleFeature->Get_Selection_Count()];
			// assign parameters ID and nIDs
			ID = m_RRdlg.Get_StationIDs(pSimpleFeature, ID, m_nIDs, PK_ColumnNumber);
			// load look up table
			m_pLUT = new CLU_Table4Col(LUT_Name,ID,m_nIDs);
			// assign time series
			m_pTS = new CTimeSeries[m_nIDs];
			m_RRdlg.Assign_TimeSeries(m_pLUT, m_nIDs, m_pTS);

			m_pChoiceGauges->Clear();
			wxString tmpName;
			for (int i = 0; i < m_nIDs; i++)
			{
				tmpName.append(wxString::Format("%d",ID[i]));
				tmpName.append(" | ");
				tmpName.append(m_pTS[i].Get_Name());
				m_pChoiceGauges->Append(tmpName);
				tmpName.Clear();
				//m_pChoiceGauges->Append(m_pTS[i].Get_Name());
			}
			m_pChoiceGauges->SetSelection(0);

			delete m_pLUT;
			delete[] ID;
			
			m_pButWeight->Enable();

		} else {
			SG_UI_Dlg_Message("Please select one ore more precipitation gauge(s)","Error: No Gauge Selected");
		}
	}
}
//---------------------------------------------------------------------

///////////////////////////////////////////////////////////
//
//	TIME SERIES FUNCTIONS
//
///////////////////////////////////////////////////////////

void C_dlg_ave_gauges::_Create_TimeSeries()
{
	wxDateTime period_begin;
	wxDateTime period_end;

	if ( m_pTS	!= NULL )
	{
		m_pTS[0].Set_Date_Begin(m_RRdlg.Get_Begin(m_pTS[0].Get_Name(),m_pTS[0].Get_date_col()));
		m_pTS[0].Set_Date_End(m_RRdlg.Get_End(m_pTS[0].Get_Name(),m_pTS[0].Get_date_col()));
		period_begin.Set(m_pTS[0].Get_Date_Begin().GetJDN());
		period_end.Set(m_pTS[0].Get_Date_End().GetJDN());

		// get the first and last date of all selected time series
		for (int i = 1; i < m_nIDs; i++)
		{
			m_pTS[i].Set_Date_Begin(m_RRdlg.Get_Begin(m_pTS[i].Get_Name(),m_pTS[i].Get_date_col()));
			m_pTS[i].Set_Date_End(m_RRdlg.Get_End(m_pTS[i].Get_Name(),m_pTS[i].Get_date_col()));
			if (m_pTS[i].Get_Date_Begin() < period_begin) period_begin.Set(m_pTS[i].Get_Date_Begin().GetJDN());
			if (m_pTS[i].Get_Date_End() > period_end) period_end.Set(m_pTS[i].Get_Date_End().GetJDN());
		}

		CDateDLG *date_dlg = new CDateDLG(g_pSAGA_Frame, wxID_ANY, wxT("Select a Period"));
		//period_begin = m_RRdlg.Get_Begin(m_pTS->Get_Name().c_str(),m_pTS->Get_date_col().c_str());
		//period_end	 = m_RRdlg.Get_End(m_pTS->Get_Name().c_str(),m_pTS->Get_date_col().c_str());
		date_dlg->Set_Date1(period_begin);
		date_dlg->Set_Date2(period_end);
		if (date_dlg->ShowModal() == wxID_OK)
		{
			m_pTS->Set_Date_Begin(date_dlg->Get_Date1());
			m_pTS->Set_Date_End(date_dlg->Get_Date2());
			m_pButOK->Enable();
		}
	} else {
		if ( m_pTS == NULL )
			SG_UI_Dlg_Message("Please select one or more gauges!","Error: No Gauge Selected");
	}
}
//---------------------------------------------------------------------
