
///////////////////////////////////////////////////////////
//                                                       //
//                         SAGA                          //
//                                                       //
//      System for Automated Geoscientific Analyses      //
//                                                       //
//                     Tool Library                      //
//                                                       //
//                       io_gdal                         //
//                                                       //
//-------------------------------------------------------//
//                                                       //
//                    ogr_import.cpp                     //
//                                                       //
//            Copyright (C) 2008 O. 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.de                    //
//                                                       //
//    contact:    Olaf Conrad                            //
//                Bundesstr. 55                          //
//                D-20146 Hamburg                        //
//                Germany                                //
//                                                       //
///////////////////////////////////////////////////////////

//---------------------------------------------------------
#include "ogr_import.h"


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

//---------------------------------------------------------
COGR_Import::COGR_Import(void)
{
	Set_Name	(_TL("Import Shapes"));

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

	Add_Reference("GDAL/OGR contributors", "2019",
		"GDAL/OGR Geospatial Data Abstraction software Library",
		"A translator library for raster and vector geospatial data formats. Open Source Geospatial Foundation.",
		SG_T("https://gdal.org"), SG_T("Link")
	);

	Set_Description(_TW(
		"The \"OGR Vector Data Import\" tool imports vector data from various file/database formats using the "
		"\"Geospatial Data Abstraction Library\" (GDAL) by Frank Warmerdam. "
	));

	Add_Description(CSG_String::Format("\nGDAL %s:%s\n", _TL("Version"), SG_Get_OGR_Drivers().Get_Version().c_str()));

	Add_Description(_TL("Following vector formats are currently supported:"), false);
	Add_Description(CSG_String::Format("\n<table border=\"1\"><tr><th>%s</th><th>%s</th><th>%s</th></tr>",
		_TL("Name"), _TL("ID"), _TL("Extension")), false
	);

	CSG_String Filter[2]; CSG_Table Drivers;
	Drivers.Add_Field("Name"     , SG_DATATYPE_String);
	Drivers.Add_Field("ID"       , SG_DATATYPE_String);
	Drivers.Add_Field("Extension", SG_DATATYPE_String);

	for(int i=0; i<SG_Get_OGR_Drivers().Get_Count(); i++)
    {
		if( SG_Get_OGR_Drivers().is_Vector(i) && SG_Get_OGR_Drivers().Can_Read(i) )
		{
			CSG_Table_Record &Driver = *Drivers.Add_Record();
			Driver.Set_Value(0, SG_Get_OGR_Drivers().Get_Name       (i));
			Driver.Set_Value(1, SG_Get_OGR_Drivers().Get_Description(i));
			Driver.Set_Value(2, SG_Get_OGR_Drivers().Get_Extension  (i));
		}
	}

	Drivers.Sort(0);

	for(sLong i=0; i<Drivers.Get_Count(); i++)
	{
		CSG_String Name(Drivers[i].asString(0)), ID(Drivers[i].asString(1)), Extension(Drivers[i].asString(2));

		Add_Description("<tr><td>" + Name + "</td><td>" + ID  + "</td><td>" + Extension + "</td></tr>", false);

		if( !Extension.is_Empty() )
		{
			Extension.Replace("/", ";");

			Filter[0] += "|" + Name + "|*." + Extension;
			Filter[1] += Filter[1].is_Empty() ? "*." : ";*.";
			Filter[1] += Extension;
		}
	}

	Add_Description("</table>", false);

	Filter[0].Prepend(CSG_String::Format("%s|%s|%s|*.*", _TL("Recognized Files"), Filter[1].c_str(), _TL("All Files")));

	//-----------------------------------------------------
	Parameters.Add_Shapes_List("",
		"SHAPES"   , _TL("Shapes"),
		_TL(""),
		PARAMETER_OUTPUT
	);

	Parameters.Add_FilePath("",
		"FILES"    , _TL("Files"),
		_TL(""),
		Filter[0], NULL, false, false, true
	);

	Parameters.Add_Choice("",
		"GEOM_TYPE", _TL("Geometry Type"),
		_TL("Some OGR drivers are unable to determine the geometry type automatically, please choose the appropriate one in this case"),
		SG_Get_OGR_WKB_Type_Choices(), 0
	);
}


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

//---------------------------------------------------------
int COGR_Import::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
{
	if( pParameter->Cmp_Identifier("FILES") )
	{
		CSG_OGR_DataSet DataSource; CSG_Strings Files; pParameter->asFilePath()->Get_FilePaths(Files);

		if( Files.Get_Count() != 1 || !DataSource.Create(Files[0]) || DataSource.Get_Count() != 1 )
		{
			pParameters->Set_Enabled("GEOM_TYPE", true);
		}
		else
		{
			pParameters->Set_Enabled("GEOM_TYPE", DataSource.Get_Geomety_Type(0, true) == wkbUnknown);
		}
	}

	return( CSG_Tool::On_Parameters_Enable(pParameters, pParameter) );
}


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

//---------------------------------------------------------
bool COGR_Import::On_Execute(void)
{
	Parameters["SHAPES"].asShapesList()->Del_Items();

	CSG_Strings Files;

	if( Parameters["FILES"].asFilePath()->Get_FilePaths(Files) )
	{
		for(int i=0; i<Files.Get_Count() && Process_Get_Okay(); i++)
		{
			Import_File(Files[i]);
		}
	}

	return( Parameters["SHAPES"].asShapesList()->Get_Item_Count() > 0 );
}

//---------------------------------------------------------
bool COGR_Import::Import_File(const CSG_String &_File)
{
	CSG_String File(_File.BeforeFirst('|'));

	Message_Fmt("\n%s: %s", _TL("loading"), File.c_str());

	CSG_OGR_DataSet DataSource;

	if( !DataSource.Create(File) )
	{
		Message_Fmt("\n%s", _TL("could not open data source"));

		return( false );
	}

	if( DataSource.Get_Count() < 1 )
	{
		Message_Fmt("\n%s", _TL("no layers in data source"));

		return( false );
	}

	//-----------------------------------------------------
	if( DataSource.Get_Count() == 1 )
	{
		return( Import_Layer(DataSource, 0) );
	}

	int Layer = -1;

	if( _File.AfterFirst('|').asInt(Layer) )
	{
		return( Import_Layer(DataSource, Layer) );
	}

	int n = 0;

	for(int i=0; i<DataSource.Get_Count() && Process_Get_Okay(); i++)
	{
		if( Import_Layer(DataSource, i) )
		{
			n++;
		}
	}

	return( n > 0 );
}

//---------------------------------------------------------
bool COGR_Import::Import_Layer(CSG_OGR_DataSet &DataSource, int Layer)
{
	CSG_Shapes *pShapes = DataSource.Read(Layer, Parameters["GEOM_TYPE"].is_Enabled() ? Parameters["GEOM_TYPE"].asInt() : 0);

	if( pShapes )
	{
		Parameters["SHAPES"].asShapesList()->Add_Item(pShapes);

		CSG_String File(DataSource.Get_File());

		if( DataSource.Get_Count() > 1 )
		{
			File += CSG_String::Format("|%d", Layer);
		}

		pShapes->Set_File_Name(File);

		pShapes->Set_Description(DataSource.Get_Description(Layer));
		pShapes->Get_MetaData().Add_Child("GDAL_DRIVER", DataSource.Get_DriverID());

		CSG_String Name(pShapes->Get_Name());

		if( Name.is_Empty() )
		{
			Name = SG_File_Get_Name(DataSource.Get_File(), false);

			if( DataSource.Get_Count() > 1 )
			{
				Name += CSG_String::Format(" [%d]", Layer);
			}

			pShapes->Set_Name(Name);
		}
	}

	return( pShapes != NULL );
}


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

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