
///////////////////////////////////////////////////////////
//                                                       //
//                         SAGA                          //
//                                                       //
//      System for Automated Geoscientific Analyses      //
//                                                       //
//                    User Interface                     //
//                                                       //
//                    Program: SAGA                      //
//                                                       //
//-------------------------------------------------------//
//                                                       //
//                 wksp_tool_library.cpp                 //
//                                                       //
//          Copyright (C) 2005 by Olaf Conrad            //
//                                                       //
//-------------------------------------------------------//
//                                                       //
// This file is part of 'SAGA - System for Automated     //
// Geoscientific Analyses'. SAGA is free software; you   //
// can redistribute it and/or modify it under the terms  //
// of the GNU General Public License as published by the //
// Free Software Foundation, either version 2 of the     //
// License, or (at your option) any later version.       //
//                                                       //
// SAGA is distributed in the hope that it will be       //
// useful, but WITHOUT ANY WARRANTY; without even the    //
// implied warranty of MERCHANTABILITY or FITNESS FOR A  //
// PARTICULAR PURPOSE. See the GNU General Public        //
// License for more details.                             //
//                                                       //
// You should have received a copy of the GNU General    //
// Public License along with this program; if not, see   //
// <http://www.gnu.org/licenses/>.                       //
//                                                       //
//-------------------------------------------------------//
//                                                       //
//    contact:    Olaf Conrad                            //
//                Institute of Geography                 //
//                University of Goettingen               //
//                Goldschmidtstr. 5                      //
//                37077 Goettingen                       //
//                Germany                                //
//                                                       //
//    e-mail:     oconrad@saga-gis.org                   //
//                                                       //
///////////////////////////////////////////////////////////

//---------------------------------------------------------
#include <wx/filename.h>

#include <saga_api/saga_api.h>

#include "res_commands.h"
#include "res_dialogs.h"

#include "helper.h"

#include "active.h"

#include "wksp_data_manager.h"
#include "wksp_data_item.h"
#include "wksp_tool_control.h"
#include "wksp_tool_manager.h"
#include "wksp_tool_library.h"
#include "wksp_tool.h"


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

//---------------------------------------------------------
CWKSP_Tool_Library::CWKSP_Tool_Library(CSG_Tool_Library *pLibrary)
{
	m_pLibrary = pLibrary;

	_Add_Tools();
}

//---------------------------------------------------------
CWKSP_Tool_Library::~CWKSP_Tool_Library(void)
{
	_Del_Tools();

	if( MDI_Get_Frame() ) // don't unload library, if gui is closing (i.e. main window == NULL)
	{
		SG_Get_Tool_Library_Manager().Del_Library(m_pLibrary);
	}
}


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

//---------------------------------------------------------
void CWKSP_Tool_Library::Update(void)
{
	for(int i=Get_Count()-1; i>=0; i--) // first remove tools that are not available anymore
	{
		CWKSP_Tool *pItem = Get_Tool(i);

		if( !m_pLibrary->Get_Tool(pItem->Get_Tool()->Get_Name()) )
		{
			Del_Item(pItem);

			Get_Control()->Delete(pItem->GetId());
		}
	}

	for(int i=0; i<m_pLibrary->Get_Count(); i++) // then add tools that are not yet present in the list
	{
		CSG_Tool *pTool = m_pLibrary->Get_Tool(i);

		if( pTool != NULL && pTool != TLB_INTERFACE_SKIP_TOOL )
		{
			for(int j=0; j<Get_Count() && pTool; j++)
			{
				if( pTool == Get_Tool(j)->Get_Tool() )
				{
					Get_Control()->SetItemText(Get_Tool(j)->GetId(), Get_Tool(j)->Get_Name()); // just in case name has changed

					pTool = NULL;
				}
			}

			if( pTool )
			{
				CWKSP_Tool *pItem = new CWKSP_Tool(pTool, m_pLibrary->Get_Menu().w_str());

				Add_Item(pItem);

				g_pTool_Ctrl->Add_Tool(GetId(), pItem);
			}
		}
	}

	Get_Control()->SortChildren(GetId());
}

//---------------------------------------------------------
void CWKSP_Tool_Library::_Add_Tools(void)
{
	for(int i=0; i<m_pLibrary->Get_Count(); i++)
	{
		CSG_Tool *pTool = m_pLibrary->Get_Tool(i);

		if( pTool != NULL && pTool != TLB_INTERFACE_SKIP_TOOL )
		{
			CWKSP_Tool *pItem = new CWKSP_Tool(pTool, m_pLibrary->Get_Menu().w_str());

			Add_Item(pItem);
		}
	}
}

//---------------------------------------------------------
void CWKSP_Tool_Library::_Del_Tools(void)
{
	for(int i=Get_Count()-1; i>=0; i--)
	{
		CWKSP_Tool *pItem = Get_Tool(i);

		Del_Item(pItem);
	}
}


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

//---------------------------------------------------------
wxString CWKSP_Tool_Library::Get_Name(void)
{
	return( m_pLibrary->Get_Name().c_str() );
}

//---------------------------------------------------------
wxString CWKSP_Tool_Library::Get_Description(void)
{
	wxString Description(Get_Online_Tool_Description(m_pLibrary->Get_File_Name().c_str()));

	if( !Description.IsEmpty() )
	{
		return( Description );
	}

	return( m_pLibrary->Get_Summary(SG_SUMMARY_FMT_HTML).c_str() );
}

//---------------------------------------------------------
wxMenu * CWKSP_Tool_Library::Get_Menu(void)
{
	wxMenu *pMenu = new wxMenu(Get_Name()), *pSubMenu;

	CMD_Menu_Add_Item(pMenu, false, ID_CMD_TOOL_OPEN);
	CMD_Menu_Add_Item(pMenu, false, ID_CMD_TOOL_RELOAD);
	CMD_Menu_Add_Item(pMenu, false, ID_CMD_WKSP_ITEM_CLOSE);
	pMenu->AppendSeparator();
	CMD_Menu_Add_Item(pMenu, false, ID_CMD_WKSP_ITEM_SEARCH);

	if( g_pTools->Get_Parameter("DOCS_EDIT")->asBool() && g_pTools->Get_Parameter("DOCS_FOLDER")->is_Enabled() && SG_Dir_Exists(g_pTools->Get_Parameter("DOCS_FOLDER")->asString()) )
	{
		pMenu->AppendSeparator();
		pMenu->Append(ID_CMD_WKSP_FIRST, _TL("Description"), pSubMenu = new wxMenu());
		CMD_Menu_Add_Item(pSubMenu, false, ID_CMD_TOOL_DESCRIPTION_RELOAD   );
		pSubMenu->AppendSeparator();
		CMD_Menu_Add_Item(pSubMenu, false, ID_CMD_TOOL_DESCRIPTION_EDIT     );
		CMD_Menu_Add_Item(pSubMenu, false, ID_CMD_TOOL_DESCRIPTION_EDIT_REFS);
	}

	return( pMenu );
}


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

//---------------------------------------------------------
bool CWKSP_Tool_Library::On_Command(int Cmd_ID)
{
	switch( Cmd_ID )
	{
	default:
		return( CWKSP_Base_Manager::On_Command(Cmd_ID) );

	case ID_CMD_WKSP_ITEM_CLOSE:
		SG_Get_Tool_Library_Manager().Del_Library(m_pLibrary);
		break;

	case ID_CMD_WKSP_ITEM_RETURN:
		break;

	//-----------------------------------------------------
	case ID_CMD_TOOL_DESCRIPTION_RELOAD:
		if( m_pLibrary->Load_Description()
		&&  g_pActive->Get_Active() == this )
		{
			g_pActive->Set_Active(NULL);
			g_pActive->Set_Active(this);
		}
		break;

	case ID_CMD_TOOL_DESCRIPTION_EDIT     : Edit_Description(Cmd_ID); break;
	case ID_CMD_TOOL_DESCRIPTION_EDIT_REFS: Edit_Description(Cmd_ID); break;
	}

	return( true );
}

//---------------------------------------------------------
bool CWKSP_Tool_Library::On_Command_UI(wxUpdateUIEvent &event)
{
	switch( event.GetId() )
	{
	default:
		return( CWKSP_Base_Manager::On_Command_UI(event) );

	case ID_CMD_WKSP_ITEM_CLOSE:
		event.Enable(true);
		break;
	}

	return( true );
}


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

//---------------------------------------------------------
CWKSP_Tool * CWKSP_Tool_Library::Get_Tool(CWKSP_Tool *pTool)
{
	for(int i=0; i<Get_Count(); i++)
	{
		if( pTool == Get_Tool(i) )
		{
			return( pTool );
		}
	}

	return( NULL );
}

//---------------------------------------------------------
CWKSP_Tool * CWKSP_Tool_Library::Get_Tool(const wxString &Tool)
{
	for(int i=0; i<Get_Count(); i++)
	{
		if( Tool == Get_Tool(i)->Get_Tool()->Get_ID().c_str() )
		{
			return( Get_Tool(i) );
		}
	}

	return( NULL );
}

//---------------------------------------------------------
CWKSP_Tool * CWKSP_Tool_Library::Get_Tool_byID(int CMD_ID)
{
	for(int i=0; i<Get_Count(); i++)
	{
		if( Get_Tool(i)->Get_Menu_ID() == CMD_ID )
		{
			return( Get_Tool(i) );
		}
	}

	return( NULL );
}


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

//---------------------------------------------------------
bool CWKSP_Tool_Library::is_Valid(void)
{
	return( m_pLibrary->is_Valid() );
}

//---------------------------------------------------------
wxString CWKSP_Tool_Library::Get_File_Name(void)
{
	return( m_pLibrary->Get_File_Name().c_str() );
}


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

//---------------------------------------------------------
bool CWKSP_Tool_Library::Edit_Description(int Cmd_ID)
{
	if( !SG_Dir_Exists(CSG_Tool::Get_Description_Source()) )
	{
		return( false );
	}

	CSG_String File, Folder(SG_File_Make_Path(CSG_Tool::Get_Description_Source(), m_pLibrary->Get_Library_Name()));

	#define Edit_File(suffix) File = SG_File_Make_Path(Folder, m_pLibrary->Get_Library_Name() + suffix, "txt");\
		if( !SG_File_Exists(File) && !DLG_Message_Confirm(wxString::Format("%s\n\n%s", _TL("Do you want to create it?"), File.c_str()), _TL("File does not exist!")) ) { return( false ); }\
		if( !SG_Dir_Exists(Folder) && !SG_Dir_Create(Folder, true) ) { SG_UI_Dlg_Error(Folder, _TL("Directory creation failed!")); return( false ); }\

	#define Edit_Text(text)   if( !SG_File_Exists(File) ) { CSG_File Stream; if( !Stream.Open(File, SG_FILE_W, false, SG_FILE_ENCODING_UTF8) ) { SG_UI_Dlg_Error(File, _TL("File creation failed!")); return( false ); }\
		Stream.Write(text); }\
		Open_Application(File.c_str());

	#define Edit_Table(table) if( !SG_File_Exists(File) ) { CSG_File Stream; if( !Stream.Open(File, SG_FILE_W, false, SG_FILE_ENCODING_UTF8) ) { SG_UI_Dlg_Error(File, _TL("File creation failed!")); return( false ); }\
		if( !table.Get_Count() ) { CSG_Table t(table); t.Add_Record(); Stream.Write(t.to_Text(false, true, true)); } else { Stream.Write(table.to_Text(false, true, true)); } }\
		CWKSP_Data_Item *pItem = g_pData->Get_byFile(File.c_str()); if( pItem ) { pItem->Get_Object()->asTable()->Reload(); } else { pItem = g_pData->Open(File.c_str(), SG_DATAOBJECT_TYPE_Table); } if( pItem ) { pItem->Show(); }\

	switch( Cmd_ID )
	{
	default                               : Edit_File(""           ); Edit_Text (m_pLibrary->Get_Description     ()); break;
	case ID_CMD_TOOL_DESCRIPTION_EDIT_REFS: Edit_File("_references"); Edit_Table(m_pLibrary->Get_References_Table()); break;
	}

	#undef Edit_File

	return( true );
}


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

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