/*******************************************************
 * Copyright (C) 2017-2020 CENOS Ltd vg@cenos-platform.com
 *
 * This file is part of CENOS.
 *
 * CENOS can not be copied and/or distributed without the express
 * permission of CENOS Ltd
 *******************************************************/
#include "FreeCadModule_Worker.h"
#include "module/FreeCadModule.h"
#include "misc/miscFunctions.hpp"
#include <boost/filesystem.hpp>


FreeCadModule_Worker::FreeCadModule_Worker(std::shared_ptr<Job>& j) : Worker(j)
{

}


messagedata FreeCadModule_Worker::run(MessageQueue_ messageQueue)
{
	FreeCadModule freecad;
	std::optional<json> input_files = assignedJob_->getArg("inputFiles");

	if (input_files.has_value())
	{
		for (auto cadfile : input_files.value().get<std::vector<std::string>>())
			freecad.addCadFile(cadfile);
	}

	messagedata returnData;

	auto runFuture = std::async(std::launch::async, &FreeCadModule_Worker::executeFreeCad, this, std::ref(freecad), std::ref(messageQueue));

	do
	{
		Sleep(100);

		if (assignedJob_->isStopRequested())
		{
			freecad.stop();
			runFuture.wait();
		}

	} while (runFuture.wait_for(std::chrono::milliseconds(1)) != std::future_status::ready);

	returnData = runFuture.get();

	return returnData;
}

messagedata FreeCadModule_Worker::executeFreeCad(FreeCadModule& freecad, MessageQueue_ messageQueue)
{
	//create instance of SalomeModule
	std::optional<json> wdir = assignedJob_->getArg("caseDir");

	if (!wdir.has_value())
		return messagedata(messagedata::error, messagedata::response, "Argument 1 not specified for Salome input defined");
	freecad.setWDir(wdir.value());
	freecad.setGuid(assignedJob_->guid());
	freecad.setPort(assignedJob_->port());

	//analyze commands

	//if (assignedJob_->command() == "runFreeCad")
	if ( (assignedJob_->command() == "runSalome") or (assignedJob_->command() == "runSalomeWithCad"))
	{
		return freecad.run();
	}
	else if (assignedJob_->command() == "updateSalome")
	{
		std::optional<json> geomdata_json = assignedJob_->getArg("geometryData");
		freecad.setGeometryData(geomdata_json);
		return freecad.update();
	}
	else
	{
		return messagedata(messagedata::error, messagedata::response, "No command " + assignedJob_->command() + " defined", assignedJob_->guid());
	}
}