
///////////////////////////////////////////////////////////
//                                                       //
//                         SAGA                          //
//                                                       //
//      System for Automated Geoscientific Analyses      //
//                                                       //
//                     Tool Library                      //
//                      dev_tools                        //
//                                                       //
//-------------------------------------------------------//
//                                                       //
//                tool_help_generator.cpp                //
//                                                       //
//                 Copyright (C) 2026 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/>.                       //
//                                                       //
//-------------------------------------------------------//
//                                                       //
//    e-mail:     oconrad@saga-gis.org                   //
//                                                       //
//    contact:    Olaf Conrad                            //
//                Institute of Geography                 //
//                University of Hamburg                  //
//                Germany                                //
//                                                       //
///////////////////////////////////////////////////////////

//---------------------------------------------------------
#include "tool_help_generator.h"


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

//---------------------------------------------------------
CTool_Descriptors_to_File::CTool_Descriptors_to_File(void)
{
	Set_Name	("Create/Update Tool Descriptors");

	Set_Author	("O.Conrad (c) 2026");

	Parameters.Add_FilePath("", "FOLDER"     , "Target Folder"                , "", NULL, NULL, true, true);
	Parameters.Add_Bool    ("", "LOADDEFS"   , "Load Default Libraries"       , "", false);

	Parameters.Add_Choice  ("", "DESC_EXISTS", "If description file exists...", "", "keep|replace"      , 0);
	Parameters.Add_Choice  ("", "REFS_EXISTS", "If references file exists..." , "", "keep|replace|merge", 0);
	Parameters.Add_Choice  ("", "PRMS_EXISTS", "If parameters file exists..." , "", "keep|replace|merge", 2);

	Parameters.Add_Bool    ("", "CATEGORY"   , "Category Folder"              , "", false);
	Parameters.Add_Choice  ("", "CONVERT"    , "Format Conversion"            , "", "no conversion|markdown");
}


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

//---------------------------------------------------------
bool CTool_Descriptors_to_File::On_Execute(void)
{
	CSG_String Root(Parameters["FOLDER"].asString());

	if( !SG_Dir_Exists(Root) && !SG_Dir_Create(Root, true) )
	{
		Error_Fmt("failed to create folder: %s", Root.c_str());

		return( false );
	}

	//---------------------------------------------------------
	if( Parameters["LOADDEFS"].asBool() )
	{
		SG_Get_Tool_Library_Manager().Add_Default_Libraries();
	}

	//---------------------------------------------------------
	for(int iLibrary=0, nTotal=0; iLibrary<SG_Get_Tool_Library_Manager().Get_Count(); iLibrary++)
	{
		CSG_Tool_Library *pLibrary = SG_Get_Tool_Library_Manager().Get_Library(iLibrary);

		if( !pLibrary->Get_Category    ().Cmp("SAGA Development"          ) // generally exclude certain categories/libraries
		||  !pLibrary->Get_Library_Name().Cmp("_tool_chains_uncategorized") )
		{
			continue;
		}

		Process_Set_Text(pLibrary->Get_Library_Name());

		//-------------------------------------------------
		CSG_String Folder(Root);

		if( Parameters["CATEGORY"].asBool() )
		{
			CSG_String Category(pLibrary->Get_Category());

			Category.Make_Lower(); Category.Replace(" & ", "_"); Category.Replace("/", "_"); Category.Replace(" ", "_");

			Folder = SG_File_Make_Path(Folder, Category);
		}

		Folder = SG_File_Make_Path(Folder, pLibrary->Get_Library_Name());

		if( !SG_Dir_Create(Folder, true) )
		{
			return( false );
		}

		//-------------------------------------------------
		Write_Library(Folder, pLibrary);

		for(int iTool=0; iTool<pLibrary->Get_Count() && Set_Progress(nTotal, SG_Get_Tool_Library_Manager().Get_Tool_Count()); iTool++, nTotal++)
		{
			SG_UI_ProgressAndMsg_Lock(true);

			Write_Tool(Folder, pLibrary, pLibrary->Get_Tool(iTool));

			SG_UI_ProgressAndMsg_Lock(false);
		}
	}

	//-----------------------------------------------------
	return( true );
}


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

//---------------------------------------------------------
bool CTool_Descriptors_to_File::Write_Library(const CSG_String &Folder, CSG_Tool_Library *pLibrary)
{
	CSG_String File(SG_File_Make_Path(Folder, pLibrary->Get_Library_Name(), "txt"));

	if( !SG_File_Exists(File) || (Parameters["DESC_EXISTS"].asInt() > 0 && pLibrary->Get_Type() != ESG_Library_Type::Chain) )
	{
		CSG_File Stream; if( !Stream.Open(File, SG_FILE_W, true, SG_FILE_ENCODING_UTF8) ) { return( false ); }

		CSG_String s(pLibrary->Get_Description());

		if( Parameters["CONVERT"].asInt() == 1 )
		{
			s = CSG_Text_Format_Converter::Html_to_Markdown(s);
		}

		Stream.Write(s);
	}

	return( true );
}


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

//---------------------------------------------------------
bool CTool_Descriptors_to_File::Write_Tool(const CSG_String &Folder, CSG_Tool_Library *pLibrary, CSG_Tool *pTool)
{
	CSG_String File, Name(pLibrary->Get_Library_Name() + "_" + pTool->Get_ID());

	File = SG_File_Make_Path(Folder, Name, "txt");

	if( !SG_File_Exists(File) || Parameters["DESC_EXISTS"].asInt() > 0 )
	{
		CSG_File Stream; if( !Stream.Open(File, SG_FILE_W, true, SG_FILE_ENCODING_UTF8) ) { return( false ); }

		CSG_String s(pTool->Get_Description());

		if( Parameters["CONVERT"].asInt() == 1 )
		{
			s = CSG_Text_Format_Converter::Html_to_Markdown(s);
		}

		Stream.Write(s);
	}

	//-----------------------------------------------------
	File = SG_File_Make_Path(Folder, Name + "_references", "txt");

	if( !SG_File_Exists(File) || Parameters["REFS_EXISTS"].asInt() > 0 )
	{
		CSG_Table Table(pTool->Get_References_Table());

		if( SG_File_Exists(File) && Parameters["REFS_EXISTS"].asInt() == 2 ) // merge
		{
			CSG_Table Merge(File);

			if( Merge.is_Compatible(Table) )
			{
				for(sLong i=0; i<Merge.Get_Count(); i++)
				{
					Table.Add_Record(Merge.Get_Record(i));
				}
			}
		}

		Table.Save(File); SG_File_Set_Extension(File, "mtab"); SG_File_Delete(File);
	}

	//-----------------------------------------------------
	File = SG_File_Make_Path(Folder, Name + "_parameters", "txt");

	if( !SG_File_Exists(File) || Parameters["PRMS_EXISTS"].asInt() > 0 )
	{
		CSG_Table Table(pTool->Get_Parameters_Table());

		if( SG_File_Exists(File) && Parameters["PRMS_EXISTS"].asInt() == 2 ) // merge
		{
			CSG_Table Merge(File);

			if( Merge.is_Compatible(Table) ) // id, name, description
			{
				for(sLong i=0; i<Merge.Get_Count(); i++)
				{
					CSG_Table_Record *pRecord = Table.Find_Record(0, Merge[i].asString(0));

					if( pRecord )
					{
						pRecord->Assign(Merge.Get_Record(i));
					}
				}
			}
		}

		Table.Save(File); SG_File_Set_Extension(File, "mtab"); SG_File_Delete(File);
	}

	return( true );
}


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

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