#include "MaterialFunctions.h"
#include <ryml.hpp>
#include "cenos_exception.h"

void writeSteelPhases(Material mat, std::string filename)
{
	double austenizationTemperatureAc1;
	double austenizationTemperatureAc3;
	double martensiteStartTemperature;
	std::vector<double> temperature1;
	std::vector<double> time1;
	std::vector<double> temperature2;
	std::vector<double> time2;
	std::string name;
	//write material file
	auto data = mat.getMaterialData();

	name = mat.getName();
	austenizationTemperatureAc1 = data["ATemp1"].getDoubleValue();
	austenizationTemperatureAc3 = data["ATemp3"].getDoubleValue();
	martensiteStartTemperature = data["MartStart"].getDoubleValue();
	std::vector<double> tstart = data["StartTime"].getValueVector();
	std::vector<double> tend = data["EndTime"].getValueVector();


	for (int i = 0; i < tstart.size() / 2; i++)
	{
		temperature1.push_back(tstart[i * 2]);
		time1.push_back(tstart[i * 2 + 1]);
	}
	for (int i = 0; i < tend.size() / 2; i++)
	{
		temperature2.push_back(tend[i * 2]);
		time2.push_back(tend[i * 2 + 1]);
	}


	ryml::Tree tree;
	ryml::NodeRef r = tree.rootref();
	r |= ryml::MAP;
	r["Name"] << name.c_str();
	r["Ac1"] << austenizationTemperatureAc1;
	r["Ac3"] << austenizationTemperatureAc3;
	r["Ms"] << martensiteStartTemperature;
	ryml::NodeRef Start_time = r["Start_time"];
	ryml::NodeRef Start_temperature = r["Start_temperature"];
	Start_time |= ryml::SEQ;
	Start_temperature |= ryml::SEQ;
	for (int i = 0; i < tstart.size() / 2; i++)
	{
		Start_time.append_child() << time1[i];
		Start_temperature.append_child() << temperature1[i];
	}


	ryml::NodeRef End_time = r["End_time"];
	ryml::NodeRef End_temperature = r["End_temperature"];
	End_time |= ryml::SEQ;
	End_temperature |= ryml::SEQ;
	for (int i = 0; i < tend.size() / 2; i++)
	{
		End_time.append_child() << time2[i];
		End_temperature.append_child() << temperature2[i];
	}


	FILE* yaml_file;
	char buffer[100];

	yaml_file = fopen(filename.c_str(), "w");
	if (yaml_file == NULL)
		throw cenos_exception("Error opening phase_properties.yaml file");

	emit(tree, yaml_file);

	fclose(yaml_file);
}