/**
* �ļ�     tunnel.cpp
* ����    ������ʵ��
* ��ϸ��Ϣ  
* ����   �������� ���䣺57862207@qq.com
* ����     2022-7-14
*/

#include "tunnel.h"
tunnel_cell::tunnel_cell(double x, double y, double z)
{
	this->x = x;
	this->y = y;
	this->z = z;
}

tunnel_cell::~tunnel_cell()
{

}

tunnel::tunnel()
{
}

//��ʼ�������б�����һϵ���߶ΰ�˳�򹹳����������·����
//�Ե�һ���߶εĶ��㿪ʼ��ÿ��һ��Ϊһ�����ӡ�
bool tunnel::init_cells()
{
	bool bRet = true;
	read_lines_from_db();
	transform_lines_to_cells();
	return bRet;
}

//��ʼ�����
bool tunnel::init_tunnel()
{
	init_cells();
}

//ͨ�����������Ż�ȡ���ӵľ�������
bool tunnel::get_position_by_cell_index(int index, point& pos)
{
	bool bRet = true;
	if (index < 0 || index >= m_vec_cells.size())
	{
		bRet = false;
		return bRet;
	}
	pos = point(m_vec_cells[index].x, m_vec_cells[index].y, m_vec_cells[index].z);
	return bRet;
}

int tunnel::get_cells_count()
{
	return m_vec_cells.size();
}

//���ڽ���վ����ӳ�䵽��Ӧ�ĸ�����������������ͨ����վ�����Ӿ�����ȷ����ǰ�������ڵĸ���
int tunnel::get_cell_index_by_position(const point& pos)
{
	//ȡ������������վ����ĵ���Ϊ��վ�ĸ��Ӻ�
	int index = 0;
	double dist_min = 1000;//
	for (int i = 0; i < m_vec_cells.size(); i++)
	{
		double dist = pos.dist(point(m_vec_cells[i].x, m_vec_cells[i].y, m_vec_cells[i].z));
		if (dist < dist_min)
		{
			dist_min = dist;
			index = i;
		}
	}
	return index;
}

tunnel::~tunnel()
{

}

//�����ݿ��ж�ȡ������������������߶�
bool tunnel::read_lines_from_db()
{
	bool ret = true;
	m_queue_lines.clear();

	std::string sql = "SELECT id, b_x, b_y, b_z, e_x, e_y, e_z FROM dat_tunnel_path_v ORDER BY id ASC;";

	std::string Error;
	YADB::CDBResultSet DBRes;
	sDBConnPool.Query(sql.c_str(), DBRes, Error);
	int nCount = DBRes.GetRecordCount(Error);
	if (nCount < 1)
	{
		log_error("��ʼ��������Ӽ�ʧ��");
		ret = false;
		return ret;
	}

	log_info("init_cells. The record count=%ld\n", nCount);

	while (DBRes.GetNextRecod(Error))
	{
		double b_x = 0.0;
		double b_y = 0.0;
		double b_z = 0.0;
		double e_x = 0.0;
		double e_y = 0.0;
		double e_z = 0.0;

		DBRes.GetField("b_x", b_x, Error);
		DBRes.GetField("b_y", b_y, Error);
		DBRes.GetField("b_z", b_z, Error);
		DBRes.GetField("e_x", e_x, Error);
		DBRes.GetField("e_y", e_y, Error);
		DBRes.GetField("e_z", e_z, Error);

		line_v tunnel_line(point(b_x, b_y, b_z), point(e_x, e_y, e_z));

		m_queue_lines.push_back(tunnel_line);

	}
	return ret;
}

//���߶ζ���ת����������Ӷ���
bool tunnel::transform_lines_to_cells()
{
	bool bRet = true;
	for (auto iter_line = m_queue_lines.begin(); iter_line != m_queue_lines.end(); iter_line++)
	{
		std::deque<point> deque_points;
		iter_line->calc_point_list(deque_points);
		for (auto iter_point = deque_points.begin(); iter_point != deque_points.end(); iter_point++)
		{
			m_vec_cells.push_back(tunnel_cell(iter_point->x, iter_point->y, iter_point->z));
		}
	}
	return bRet;
}