// STFile.cpp: implementation of the CSTFile class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "UDPServ.h"
#include "STFile.h"
#include "STFileLine.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CSTFile::CSTFile()
{

}

CSTFile::~CSTFile()
{
	POSITION pos;

	if (!!m_listVehicle.IsEmpty())
	{
		for( pos = m_listVehicle.GetHeadPosition(); pos != NULL; )
		{
			delete m_listVehicle.GetNext( pos );
		}

		m_listVehicle.RemoveAll();
	}
}

void CSTFile::SetGPSInfo(CString strVehicle, CString strLat, CString strLong, CString strToken, CString strLable)
{
	m_strVehicle = strVehicle;
	m_strLat = strLat;
	m_strLong = strLong;
	m_strToken = strToken;
	m_strLable = strLable;
}

void CSTFile::SaveFile()
{
	POSITION pos;
	CString strGPSLine;

	Add();	// add new GPS info

	if (!m_listVehicle.IsEmpty())
	{
		if(!m_GPSFile.Open(m_strFileName, CFile::modeCreate | CFile::modeWrite, &e))
		{
			#ifdef _DEBUG
			afxDump << "File could not be opened " << e.m_cause << "\n";
			#endif
		}

		for( pos = m_listVehicle.GetHeadPosition(); pos != NULL; )
		{
			strGPSLine = ((CSTFileLine*)(m_listVehicle.GetNext( pos )))->GetStFileLine();
			m_GPSFile.Write(strGPSLine, strGPSLine.GetLength());
		}

		m_GPSFile.Close();
	}
}

void CSTFile::SetGPSFileName(CString strFileName)
{	
	m_strFileName = strFileName;
}

void CSTFile::Add()
{
	POSITION pos = NULL;
	CSTFileLine* cptrNewVehicle;

	if (!m_listVehicle.IsEmpty())
	{
		for (pos = m_listVehicle.GetHeadPosition(); 
				pos != NULL && ((CSTFileLine*)(m_listVehicle.GetAt(pos)))->m_strVehicle != m_strVehicle;
				m_listVehicle.GetNext( pos ));
	}

	if (pos)	// in list
	{
		((CSTFileLine*)(m_listVehicle.GetAt(pos)))->m_strLat = m_strLat;
		((CSTFileLine*)(m_listVehicle.GetAt(pos)))->m_strLong = m_strLong;
		((CSTFileLine*)(m_listVehicle.GetAt(pos)))->m_strToken = m_strToken;
		((CSTFileLine*)(m_listVehicle.GetAt(pos)))->m_strLable = m_strLable;
	}
	else
	{
		cptrNewVehicle = new CSTFileLine;
		m_listVehicle.AddHead(cptrNewVehicle);

		cptrNewVehicle->m_strVehicle = m_strVehicle;
		cptrNewVehicle->m_strLat = m_strLat;
		cptrNewVehicle->m_strLong = m_strLong;
		cptrNewVehicle->m_strToken = m_strToken;
		cptrNewVehicle->m_strLable = m_strLable;
	}
}