/*
 * DriverCommon.cpp
 *
 *  Created on: 2024年11月1日
 *      Author: ZhangChundi
 */

#include "DriverCommon.h"

DriverCommon::DriverCommon() {
	// TODO Auto-generated constructor stub

}

DriverCommon::~DriverCommon() {
	// TODO Auto-generated destructor stub
}

std::vector<std::string> DriverCommon::split(const std::string &str,
		char delimiter) {
	std::vector<std::string> tokens;
	std::string token;
	std::istringstream tokenStream(str);
	while (std::getline(tokenStream, token, delimiter)) {
		tokens.push_back(token);
	}
	// 如果字符串以分隔符结尾，则最后一个空字符串会被添加到tokens中，需要去除
	if (!tokens.empty() && tokens.back().empty()) {
		tokens.pop_back();
	}
	return tokens;
}


std::optional<FlowMessage> DriverCommon::analysisFlowFile(std::string filePath) {
	if (!fileExists(filePath)){
		return std::nullopt;
	}
	std::ifstream file(filePath);
	if (!file.is_open()) {
		std::cerr << "Failed to open file!" << std::endl;
		std::runtime_error("Failed to open file: " + filePath);
	}

	nlohmann::json j;
	file >> j;

	FlowMessage config = j.get<FlowMessage>();

	// 简单打印测试
	for (const auto& item : config.testItems) {
		std::cout << "FuncName: " << item.funcName << ", FuncId: " << item.funcId << std::endl;
		for (const auto& result : item.results) {
			std::cout << "    Result Param: " << result.paramName << ", Max: " << result.max << std::endl;
		}
	}

	return config;
}

std::optional<Setting> DriverCommon::analysisSettingFile(std::string filePath) {
	if (!fileExists(filePath)){
		return std::nullopt;
	}
	std::ifstream file(filePath);
	if (!file.is_open()) {
		std::cerr << "Failed to open file!" << std::endl;
		std::runtime_error("Failed to open file: " + filePath);
	}
	nlohmann::json j;
	file >> j;
	Setting config = j.get<Setting>();
	return config;
}

bool DriverCommon::fileExists(const std::string& path) {
    return std::filesystem::exists(path);
}
