/*
*
*	Example implementation for "Accurate Rendering of Liquid-Crystals and Inhomogeneous Optically Anisotropic Media"
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/

#include <string>
#include <filesystem>
#include <thread>
#include <chrono>
#include <cassert>
#include <getopt.h>

#include "../src/profiles_manager.hpp"

int main(int argc, char* argv[]) {
	std::string name, path;
	bool async = true;
	{
		option long_options[] = {
			{"path", required_argument, NULL, 'p'},
			{"name", required_argument, NULL, 'n'},
			{"noasync", no_argument, NULL, 's'},
			{NULL, 0, NULL, 0}
		};

		char ch;
		while ((ch = getopt_long(argc, argv, "p:n:s", long_options, NULL)) != -1) {
			switch (ch) {
			case 'n':
				name = optarg;
				break;
			case 'p':
				path = optarg;
				break;
			case 's':
				async = false;
				break;
			}
		}
	}

	if (!path.length() || !name.length()) {
		std::cout << "Usage: importer --name=<new profile name> --path=<generated profile path>" << std::endl;
		return 1;
	}
	
	profiles_manager profiles;

	// Start import
	const std::filesystem::path import_path{ path };
	std::cout << "Importing '" << name << "', path: '" << import_path.string() << "'..." << std::endl;
	if (!async)
		std::cout << "Running synchronous!" << std::endl;

	profiles.start_new_import_job(name, import_path, async);
	assert(profiles.profile_jobs.size());

	// Wait for finish
	for (;;) {
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
		profiles.update_jobs();

		if (profiles.profile_jobs.front().status != profiles_manager::profile_job_t::status_t::pending)
			return profiles.profile_jobs.front().status == profiles_manager::profile_job_t::status_t::error ? 1 : 0;
	}
}
