#include "ConfigServer.h"
#include <fstream>
#include "nlohmann/json.hpp"
#include <iostream>

using namespace std;
using json = nlohmann::json;

const int versionConfig = 1;

bool loadConfig(std::string path, ConfigSetting& res)
{
	ifstream f(path);
	if (f.fail())
		return false;

	json data;
	try
	{
		data = json::parse(f);

		res.versionIIS = data["versionIIS"];
		if (res.versionIIS != versionConfig)
		{
			std::cerr << "[loadConfig] Wrong version config JSON " << std::endl;
			return false;
		}

		res.maxImagesInQueue = data.value("maxImagesInQueue", 1);
		if (res.maxImagesInQueue > maxImages)
			res.maxImagesInQueue = maxImages;
		res.gpuObjects = data.value("gpuObjects", 1);
		if (res.gpuObjects < 1)
			res.gpuObjects = 1;
		if (res.gpuObjects > maxGPUObjects)
			res.gpuObjects = maxGPUObjects;
		res.pathToConfigForLibrary = data.value("pathToConfigForLibrary", "");
		res.detectConfThresh = data.value("detectConfThresh", res.detectConfThresh);
		res.minPlateHeight = data.value("minPlateHeight", res.minPlateHeight);
		res.minPlateWidth = data.value("minPlateWidth", res.minPlateWidth);
		res.minSymbolsPlate = data.value("minSymbolsPlate", res.minSymbolsPlate);
		res.maxSymbolsPlate = data.value("maxSymbolsPlate", res.maxSymbolsPlate);
		res.expandedResult = data.value("expandedResult", res.expandedResult);
		res.plateTemplates = data["plateTemplates"].get<std::vector<string>>();
		res.port = data.value("port", res.port);
		res.mode = data.value("mode", res.mode);
	}

	catch (json::parse_error& ex)
	{
		std::cerr << "[loadConfig] parse error at byte " << ex.byte << std::endl;
		return false;
	}


	return true;
}