/* GPC (C) 2017-2018 Stephane Charette <stephanecharette@gmail.com>
 * $Id: SessionComponentLoader.cpp 2492 2018-03-21 06:22:15Z stephane $
 */

#include "GPC.hpp"


SessionComponentLoader::SessionComponentLoader(SessionComponent &sc) :
	ThreadWithProgressWindow(sc.session_record.field[SessionRecord::EField::kIjsFilename], true, false, 10000, "", &sc),
	parent(sc)
{
	return;
}


SessionComponentLoader::~SessionComponentLoader(void)
{
	return;
}


void SessionComponentLoader::run(void)
{
	parent.setEnabled(false);
	parent.setVisible(false);

	const size_t number_of_images_to_load = std::stoi(parent.session_record.field[SessionRecord::EField::kNumberOfImages]);
	double total_number_of_items = 1.0 + number_of_images_to_load;

	File file = parent.session_record.get_ijs_file();
	setStatusMessage("Loading " + file.getFileName() + "...");
	setProgress(1.0 / total_number_of_items);
	LOG_MSG("loading " << file.getFullPathName().toStdString());

	parent.print_job.load_ijs(file);

	for (size_t image_index = 0; image_index < number_of_images_to_load && threadShouldExit() == false; image_index++)
	{
		// every once in a while it looks like something is making the parent canvas visible,
		// which we don't want, so make sure it is hidden while we're still loading images
		parent.setVisible(false);

		const auto * bitmap = parent.print_job.ijs.bitmaps[image_index];
		setStatusMessage("Loading " + String(bitmap->short_filename) + "...");
		setProgress((image_index + 2.0) / total_number_of_items);
		LOG_MSG("loading " << bitmap->short_filename);

		parent.print_job.load_ijb(image_index);
	}

	parent.table.updateContent();
	parent.setEnabled(true);
	parent.setVisible(true);

	// sometimes the progress thread window remains visible after run()
	// has finished, so be explicit about when it should be hidden
	getAlertWindow()->setVisible(false);

	return;
}

