/********************************************************
* @file     QTForPCHelper.h
* @brief    QT windows序列化接口
* @details  QT windows序列化接口
*********************************************************/
#pragma once
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <type_traits>
#include <memory>

using namespace std;

using std::string;
using std::map;
using std::vector;
typedef void QT_VOID;
typedef const char *  QT_CSTR;
typedef QT_CSTR    QT_MAP;
typedef QT_VOID(*QT_AB_CB)(const std::string &value);


static const char * qt_delim_line = "#L#";
static const char * qt_delim_key = "*F*";
static const int  qt_key_num = 2;


namespace QT
{
	namespace Helper
	{
		template<class C>
		static size_t QT_Split(const string &src, C& c, const string& delims)
		{
			size_t i = 0, j = 0, n = 0;
			while (true)
			{
				n++;
				j = src.find(delims, i);
				if (j == string::npos)
				{
					c.push_back(src.substr(i));
					break;
				}

				c.push_back(src.substr(i, j - i));
				i = j + delims.length();
			}
			return n;
		}

		//序列化
		static void QT_Serializable(std::string &qt_serializableStr, map<string, string> dataMap)
		{
			if (dataMap.empty())
				return;
			for (auto itor = dataMap.begin(); itor != dataMap.end(); ++itor)
				qt_serializableStr += itor->first + qt_delim_key + itor->second + qt_delim_line;
			return;
		}

		//反序列化
		static map<string, string> QT_DeserializePerson(QT_MAP pstr)
		{
			map<string, string> dataMap;
			if (nullptr == pstr)
				return dataMap;
			string strData = pstr;
			vector<std::string> args;

			QT_Split(strData, args, qt_delim_line);

			int sLen = args.size();
			for (int i = 0; i < sLen; i++)
			{
				string keyData = args.at(i);
				if (keyData.empty())
					continue;
				vector<string> keyargs;
				QT_Split(keyData, keyargs, qt_delim_key);
				if (qt_key_num == keyargs.size())
					dataMap.insert(std::make_pair(keyargs[0], keyargs[1]));
			}
			return dataMap;
		}

		static string vectorToString(const vector<string>& vec, const string& delimiter) {
			std::ostringstream result;
			for (size_t i = 0; i < vec.size(); ++i) {
				result << vec[i];
				if (i < vec.size() - 1) {
					result << delimiter; // 不在最后一个元素后添加分隔符
				}
			}
			return result.str(); // 返回最终字符串
		}

		static vector<string> stringToVector(const string& str, const string& delimiter) {
			vector<string> vec;
			size_t start = 0, end = 0;

			while ((end = str.find(delimiter, start)) != std::string::npos) {
				vec.push_back(str.substr(start, end - start)); // 提取子串
				start = end + delimiter.length(); // 更新起始位置
			}
			vec.push_back(str.substr(start)); // 添加最后一个元素
			return vec; // 返回字符串向量
		}
	}
}
