/***************************************
	Auteur : Pierre Aubert
	Mail : pierre.aubert@lapp.in2p3.fr
	Licence : CeCILL-C
****************************************/

#include <sstream>
#include "ProgressBarr.h"
#include "OptionParser.h"
#include "PImagePng.h"

#include "MatrixHdf5.h"

///Create the OptionParser of this program
/**	@return OptionParser of this program
*/
OptionParser createOptionParser(){
	OptionParser parser(true, __PROGRAM_VERSION__);
	parser.setExampleLongOption("gray_scott2pic --input=file.h5 --output=/output/dir/name");
	parser.setExampleShortOption("gray_scott2pic -i file.h5 -o /output/dir/name");
	
	parser.addOption("input", "i", OptionType::FILENAME, true, "input hdf5 file name");
	
	std::string defaultOutputDir("./");
	parser.addOption("output", "o", defaultOutputDir, "Output directory of the created images");
	
	return parser;
}

///Simulate the images
/**	@param inputFile : input hdf5 file name
 * 	@param outputDir : Output directory of the created images
 * 	@return true on succsess, false otherwise
*/
bool simulateImage(const std::string & inputFile, const std::string & outputDir){
	MatrixHdf5 fullMat;
	fullMat.read(inputFile);
	size_t nbImage(fullMat.getNbEntries()), nbRow(fullMat.getNbRow()), nbCol(fullMat.getNbCol());
	
	std::cout << "simulateImage : nbImage = "<<nbImage<<", nbRow = " << nbRow << ", nbCol = " << nbCol << std::endl;
	PImagePng image;
	if(!image.createImage(nbCol, nbRow, PImagePng::RGB)){
		std::cerr << "simulateImage : cannot create image" << std::endl;
		return false;
	}
	PColorMap colorMap;
	colorMap.addColor(0.0, "000000");
	colorMap.addColor(0.2, "00FF00");
	colorMap.addColor(0.21, "FFFF00");
	colorMap.addColor(0.4, "FF0000");
	colorMap.addColor(0.6, "FFFFFF");
	ProgressBarr progress(nbImage);
	for(size_t i(0lu); i < nbImage; ++i){
		progress.progress(i);
		float * matValue = fullMat.getTabMat(i);
		image.setColor(matValue, nbRow, nbCol, colorMap);
		std::stringstream fileName;
		fileName << outputDir << i << ".png";
		if(!image.write(fileName.str())){
			std::cerr << "simulateImage : cannot save image " << i << " in file '"<<fileName.str()<<"'" << std::endl;
			return false;
		}
	}
	progress.finish();
	std::cerr << "Done" << std::endl;
	return true;
}

int main(int argc, char** argv){
	OptionParser parser = createOptionParser();
	parser.parseArgument(argc, argv);
	const OptionMode & defaultMode = parser.getDefaultMode();
	std::string inputFile("");
	defaultMode.getValue(inputFile, "input");
	std::string outputDir("./");
	defaultMode.getValue(outputDir, "output");
	bool b(simulateImage(inputFile, outputDir));
	return b - 1;
}



