#include "CivTrackingResultCache.h"
#include "CivPgConn.h"

void CivTrackingResultCache::cacheInfoFromDb(CivDbConn* dbConn)
{
	if (dbConn == nullptr)
		return;

	cacheJunctionInfoFromDb(dbConn);
	cachePipeInfoFromDb(dbConn);
}


void CivTrackingResultCache::getNodeInfoBySn(const std::string& sn, Junctions& junctions)
{
	auto iterm = mNodeCache.find(sn);
	if (iterm == mNodeCache.end())
		return;

	junctions = iterm->second;
}

void CivTrackingResultCache::getPipeInfoBySn(const std::string& sn, Pipes& pipes)
{
	auto iterm = mPipesCache.find(sn);
	if (iterm == mPipesCache.end())
		return;

	pipes = iterm->second;
}

void CivTrackingResultCache::transformToJsonStr(std::string jsonStr)
{
	jsonStr.append("{node:[");

	// 拼接节点缓存数据
	jsonStr.append("{");
	for (auto iter = mNodeCache.begin(); iter != mNodeCache.end(); iter++)
	{

		std::string sNo = iter->first;
		Junctions junctions = iter->second;
	}
	jsonStr.append("}");
	jsonStr.append("],link:[");

	// 拼接管段缓存数据
	jsonStr.append("{");
	for (auto iter = mPipesCache.begin(); iter != mPipesCache.end(); iter++)
	{

	}
	jsonStr.append("}]");
	jsonStr.append("}");
}

void CivTrackingResultCache::cacheJunctionInfoFromDb(CivDbConn* dbConn)
{
	if (dbConn == nullptr)
		return;

	std::vector<std::vector<std::string>> nodeResult;
	std::vector<std::string> fileds;

	fileds.push_back("本点号");
	fileds.push_back("ST_X(geom) as xCoord");
	fileds.push_back("ST_Y(geom) as yCoord");

	if (!dbConn->getFieldValueFromTable(PIPENODE, fileds, nodeResult))
	{
		return;
	}

	// 缓存节点数据
	int rows = nodeResult.size();
	
	for (int i = 0; i < rows; i++)
	{
		if (nodeResult[i].size() < 3)
			return;

		Junctions junction;
		std::string sn = nodeResult[i][0];
		junction.sNo = sn;
		junction.xCoord = nodeResult[i][1];
		junction.yCoord = nodeResult[i][2];
		
		mNodeCache[sn] = junction;
	}
	
}

void CivTrackingResultCache::cachePipeInfoFromDb(CivDbConn* dbConn)
{
	if (dbConn == nullptr)
		return;

	std::vector<std::vector<std::string>> pipeResult;
	std::vector<std::string> fileds;

	fileds.push_back("编号");
	fileds.push_back("ST_X(ST_StartPoint(ST_GeometryN(geom, 1))) as startX");
	fileds.push_back("ST_Y(ST_StartPoint(ST_GeometryN(geom, 1))) as startY");
	fileds.push_back("ST_X(ST_EndPoint(ST_GeometryN(geom, 1))) as endX");
	fileds.push_back("ST_Y(ST_EndPoint(ST_GeometryN(geom, 1))) as endY");

	if (!dbConn->getFieldValueFromTable(PIPELINE,fileds, pipeResult))
	{
		return;
	}

	// 缓存节点数据
	int rows = pipeResult.size();

	for (int i = 0; i < rows; i++)
	{
		if (pipeResult[i].size() < 5)
			return;

		Pipes pipes;
		std::string sn = pipeResult[i][0];
		pipes.sNo = sn;
		pipes.startX= pipeResult[i][1];
		pipes.startY = pipeResult[i][2];
		pipes.endX = pipeResult[i][3];
		pipes.endY = pipeResult[i][4];

		mPipesCache[sn] = pipes;
	}
}

