#include "CivGraphFactory.h"
#include "CivGraphList.h"
#include "CivDbConn.h"
#include "CivPgConn.h"
#include "CivTrackingResultCache.h"

CivGraphFactory::CivGraphFactory()
{

}

bool  CivGraphFactory::initGraph(CivDbConn* dbConn, ALGraph<CivGraphJunction, CivGraphEdage>* graph)
{
	if (graph == nullptr)
		return false;

	if (dbConn == nullptr)
		return false;


	// 顶点坐标
	CivCoordinates coords;
	dbConn->getCoordinates(coords);

	std::list<CivCoordinates::CoordTable> coordTableLis = coords.mTables;
	std::list<CivCoordinates::CoordTable>::iterator iter;
	for (iter = coordTableLis.begin(); iter != coordTableLis.end(); iter++)
	{
		CivCoordinates::CoordTable coordTable = *iter;

		// 插入顶点数据
		CivGraphJunction graphJunction(coordTable.ID, coordTable.XCoord, coordTable.YCoord);
		graph->insertAVertex(graphJunction);
	}

	// 管段
	CivPipe civPipe;
	dbConn->getPipe(civPipe);

	std::list<CivPipe::PipesTable> pipesTableLis = civPipe.mTables;
	std::list<CivPipe::PipesTable>::iterator pIter;
	for (pIter = pipesTableLis.begin(); pIter != pipesTableLis.end(); pIter++)
	{
		CivPipe::PipesTable pipeTable = *pIter;

		// 获取管段起点坐标
		CivGraphJunction graphJunction1(pipeTable.Node1);
		int index1 = graph->getVertexIndex(graphJunction1);
		CivGraphJunction sStartjuction = graph->getData(index1);

		// 获取管段终点坐标值
		CivGraphJunction graphJunction2(pipeTable.Node2);
		int index2 = graph->getVertexIndex(graphJunction2);
		CivGraphJunction endJunction = graph->getData(index2);

	
		if (sStartjuction.getHead() > endJunction.getHead())
		{
			CivGraphEdage edAge(pipeTable.ID, pipeTable.Length, { sStartjuction.getXCoord(),sStartjuction.getYCoord(),endJunction.getXCoord(),endJunction.getYCoord() });
			graph->insertAEdge(sStartjuction, endJunction, edAge);
		}
			
		else
		{
			CivGraphEdage edAge(pipeTable.ID, pipeTable.Length, {endJunction.getXCoord(),endJunction.getYCoord(), sStartjuction.getXCoord(),sStartjuction.getYCoord() });
			graph->insertAEdge(endJunction, sStartjuction, edAge);
		}
			
	}

	return true;
}