
///////////////////////////////////////////////////////////
//                                                       //
//                         SAGA                          //
//                                                       //
//      System for Automated Geoscientific Analyses      //
//                                                       //
//                     Tool Library                      //
//                       image_io                        //
//                                                       //
//-------------------------------------------------------//
//                                                       //
//                 image_import_exif.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 "image_import_exif.h"

//---------------------------------------------------------
#if HAVE_EXIV2

#include <exiv2/exiv2.hpp>


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

//---------------------------------------------------------
bool CEXIV_Helper::Get_Coordinate(Exiv2::ExifData &exifData, double &Lon, double &Lat)
{
	auto lon    = exifData.findKey(Exiv2::ExifKey("Exif.GPSInfo.GPSLongitude"   )); if( lon == exifData.end() || lon->value().count() != 3 ) { return( false ); }
	Lon         = SG_Degree_To_Decimal(Get_Rational(lon->value(), 0), Get_Rational(lon->value(), 1), Get_Rational(lon->value(), 2));
	auto lonRef = exifData.findKey(Exiv2::ExifKey("Exif.GPSInfo.GPSLongitudeRef"));
	if( lonRef != exifData.end() && lonRef->value().toString() == "W" ) { Lon *= -1; }

	auto lat    = exifData.findKey(Exiv2::ExifKey("Exif.GPSInfo.GPSLatitude"    )); if( lat == exifData.end() || lat->value().count() != 3 ) { return( false ); }
	Lat         = SG_Degree_To_Decimal(Get_Rational(lat->value(), 0), Get_Rational(lat->value(), 1), Get_Rational(lat->value(), 2));
	auto latRef = exifData.findKey(Exiv2::ExifKey("Exif.GPSInfo.GPSLatitudeRef" ));
	if( latRef != exifData.end() && latRef->value().toString() == "S" ) { Lat *= -1; }

	return( true );
}

bool CEXIV_Helper::Get_Coordinate(Exiv2::ExifData &exifData, CSG_Point &Coordinate)
{
	return( Get_Coordinate(exifData, Coordinate.x, Coordinate.y) );
}

//---------------------------------------------------------
double CEXIV_Helper::Get_Rational(const Exiv2::Value &Value, const size_t Position)
{
	return( Value.toRational(Position).first / static_cast<double>(Value.toRational(Position).second) );
}

//---------------------------------------------------------
bool CEXIV_Helper::Get_MetaData(const CSG_String &File, CSG_MetaData &MetaData, bool bConvertRationals)
{
	CSG_String Error; return( Get_MetaData(File, MetaData, Error, bConvertRationals) );
}

bool CEXIV_Helper::Get_MetaData(const CSG_String &File, CSG_MetaData &MetaData, CSG_String &Error, bool bConvertRationals)
{
	if( SG_File_Exists(File) == false )
	{
		Error.Printf("%s\n%s: %s", _TL("File does not exist!"), _TL("File"), File.c_str());

		return( false );
	}

	std::unique_ptr<Exiv2::Image> pImage;

	try
	{
		pImage = Exiv2::ImageFactory::open(File.to_StdString());

		pImage->readMetadata();
	}
	catch( Exiv2::Error &e )
	{
		Error.Printf("%s\n%s: %s", CSG_String(e.what()).c_str(), _TL("File"), File.c_str());

		return( false );
	}
	catch(...)
	{
		Error.Printf("%s\n%s: %s", _TL("File open error!"), _TL("File"), File.c_str());

		return( false );
	}

	//-----------------------------------------------------
	MetaData.Del_Children(); MetaData.Set_Name("Exif"); MetaData.Add_Property("FILE", File);

	#define Add_Value { CSG_String key(i->key().c_str());\
		if( !bConvertRationals || (i->typeId() != Exiv2::TypeId::signedRational && i->typeId() != Exiv2::TypeId::unsignedRational) )\
		{\
			MetaData.Add_Child(key, CSG_String(i->value().toString().c_str()));\
		}\
		else if( i->value().count() == 1 )\
		{\
			MetaData.Add_Child(key, Get_Rational(i->value()));\
		}\
		else for(size_t j=0; j<i->value().count(); j++)\
		{\
			MetaData.Add_Child(key + CSG_String::Format(".%d", j), Get_Rational(i->value(), j));\
		}\
	}

	//-----------------------------------------------------
	Exiv2::ExifData &exifData = pImage->exifData(); exifData.sortByKey();

	for(Exiv2::ExifData::const_iterator i=exifData.begin(), end=exifData.end(); i!=end; i++)
	{
		Add_Value;
	}

	//-----------------------------------------------------
	Exiv2::XmpData &xmpData = pImage->xmpData(); xmpData.sortByKey();

	for(Exiv2::XmpData::const_iterator i=xmpData.begin(), end=xmpData.end(); i!=end; i++)
	{
		Add_Value;
	}

	//-----------------------------------------------------
	Exiv2::IptcData &iptcData = pImage->iptcData(); iptcData.sortByKey();

	for(Exiv2::IptcData::const_iterator i=iptcData.begin(), end=iptcData.end(); i!=end; i++)
	{
		Add_Value;
	}

	//-----------------------------------------------------
	#undef Add_Value

	return( true );
}


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

//---------------------------------------------------------
CImage_Import_Exif::CImage_Import_Exif(void)
{
	Set_Name		(_TL("Import Image Metadata"));

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

	Set_Description	(_TW(
		"This tool extracts metadata from image files if available conform to the "
		"<i>Exchangeable Image File Format</i> (Exif) specification. "
	));

	Add_Description(CSG_String::Format("<hr><p>Exiv2 version is <b>%d.%d.%d</b></p>",
		EXIV2_MAJOR_VERSION,
		EXIV2_MINOR_VERSION,
		EXIV2_PATCH_VERSION)
	);

	Add_Reference("https://exiv2.org/", SG_T("Exiv2 C++ metadata library"));

	//-----------------------------------------------------
	Parameters.Add_Table("", "TABLE", _TL("Metadata"), _TL(""), PARAMETER_OUTPUT);

	Parameters.Add_FilePath("", "FILE", _TL("File"), _TL(""), CSG_String::Format(
		"%s"                        "|*.jpg;*.jif;*.jpeg;*.raw;*.dng;*.JPG;*.JIF;*.JPEG;*.RAW;*.DNG|"
		"%s (*.jpg, *.jif, *.jpeg)" "|*.jpg;*.jif;*.jpeg;*.JPG;*.JIF;*.JPEG|"
		"%s (*.raw, *.dng)" 		"|*.raw;*.dng;*.RAW;*.DNG|"
		"%s"                        "|*.*",
		_TL("Recognized File Types"),
		_TL("JPEG - JFIF Compliant"),
		_TL("RAW Images"           ),
		_TL("All Files"            )), NULL, false, false, false
	);

	Parameters.Add_Bool("", "TYPE"     , _TL("Value Type"), _TL("Include value type information."), false);

	Parameters.Add_Bool("", "UNDEFINED", _TL("Undefined" ), _TL("Include metadata with undefined value type."), true);
}


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

//---------------------------------------------------------
bool CImage_Import_Exif::On_Execute(void)
{
	CSG_String File = Parameters["FILE"].asString();

	if( SG_File_Exists(File) == false )
	{
		Error_Fmt("%s\n%s: %s", _TL("File does not exist!"), _TL("File"), File.c_str());

		return( false );
	}

	std::unique_ptr<Exiv2::Image> pImage;

	try
	{
		pImage = Exiv2::ImageFactory::open(File.to_StdString());

		pImage->readMetadata();
	}
	catch( Exiv2::Error &e )
	{
		Error_Fmt("%s\n%s: %s", CSG_String(e.what()).c_str(), _TL("File"), File.c_str());

		return( false );
	}
	catch(...)
	{
		Error_Fmt("%s\n%s: %s", _TL("File open error!"), _TL("File"), File.c_str());

		return( false );
	}

	//-----------------------------------------------------
	#define Add_Value(type, key, value) { CSG_Table_Record &r = *Table.Add_Record(); r.Set_Value(_TL("Type"), type); r.Set_Value(_TL("Key"), key); r.Set_Value(_TL("Value"), value); }

	CSG_Table &Table = *Parameters["TABLE"].asTable();

	Table.Create(); Table.Fmt_Name("%s [Exif Metadata]", SG_File_Get_Name(File, true).c_str());

	Table.Add_Field(_TL("Key"  ), SG_DATATYPE_String);
	Table.Add_Field(_TL("Value"), SG_DATATYPE_String);

	if( Parameters["TYPE"].asBool() )
	{
		Table.Add_Field(_TL("Type"), SG_DATATYPE_String, 1);
	}

	bool bUndefined = Parameters["UNDEFINED"].asBool();

	//-----------------------------------------------------
	Exiv2::ExifData &exifData = pImage->exifData(); exifData.sortByKey();

	for(Exiv2::ExifData::const_iterator i=exifData.begin(), end=exifData.end(); i!=end; i++)
	{
		if( bUndefined || i->typeId() != Exiv2::TypeId::undefined )
		{
			Add_Value(i->typeName(), i->key().c_str(), i->value().toString().c_str());
		}
	}

	//-----------------------------------------------------
	Exiv2::XmpData &xmpData = pImage->xmpData(); xmpData.sortByKey();

	for(Exiv2::XmpData::const_iterator i=xmpData.begin(), end=xmpData.end(); i!=end; i++)
	{
		if( bUndefined || i->typeId() != Exiv2::TypeId::undefined )
		{
			Add_Value(i->typeName(), i->key().c_str(), i->value().toString().c_str());
		}
	}

	//-----------------------------------------------------
	Exiv2::IptcData &iptcData = pImage->iptcData(); iptcData.sortByKey();

	for(Exiv2::IptcData::const_iterator i=iptcData.begin(), end=iptcData.end(); i!=end; i++)
	{
		if( bUndefined || i->typeId() != Exiv2::TypeId::undefined )
		{
			Add_Value(i->typeName(), i->key().c_str(), i->value().toString().c_str());
		}
	}

	//-----------------------------------------------------
	DataObject_Update(&Table, SG_UI_DATAOBJECT_SHOW_MAP);

	return( true );
}


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

//---------------------------------------------------------
#endif // HAVE_EXIV2
