#include "DirectoryBasedMetadataReader.hxx"
#include <CLAM/XMLStorage.hxx>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>

namespace CLAM {

DirectoryBasedMetadataReader::DirectoryBasedMetadataReader()
{
}

DirectoryBasedMetadataReader::~DirectoryBasedMetadataReader()
{
}

void DirectoryBasedMetadataReader::ReadMetadata(std::string& argDirectoryPath, std::vector<CLAM::SampleMetadata>& argMetadataVector)
{
	struct dirent *directoryEntryPtr;

	DIR * directoryPtr = opendir ( argDirectoryPath.c_str() );
	if (directoryPtr == NULL)
		throw CLAM::BadFilenameException();

	while (directoryEntryPtr = readdir(directoryPtr))
	{
		if (strncmp(directoryEntryPtr->d_name, ".", 1) == 0) continue;
		if (strstr(directoryEntryPtr->d_name, ".xml") == NULL) continue;

		std::string absolutePath = argDirectoryPath + std::string("/") + std::string(directoryEntryPtr->d_name);
//		std::cout << "DirectoryBasedMetadataReader:ReadMetadata; found XML file: " << absolutePath << std::endl;
		CLAM::SampleMetadata sampleConfig;
		CLAM::XMLStorage::Restore(sampleConfig, absolutePath);
		sampleConfig.ConfigureAfterRestore();
		argMetadataVector.push_back( sampleConfig );

	}
	closedir(directoryPtr);
}

} // end namespace CLAM

