/*
 * CStringDump.cpp
 *
 *  Created on: 16.05.2015
 *      Author: Dag
 */

#include <assert.h>
#include <stdio.h>

#include "CStringDump.h"

using namespace std;


CStringDump::CStringDump(string sBaseFileName)
{
	assert (!sBaseFileName.empty());

	m_sBaseFileName = sBaseFileName;
	m_pFile = 0;
	m_Count = 0;
}

CStringDump::~CStringDump()
{
	if (m_pFile)
		fclose (m_pFile);
	m_sList.clear();
}

void CStringDump::Add(string sLine)
{
	if (!m_pFile)
		return;

	m_sList.push_back(sLine);
	m_Count++;
}

void CStringDump::Dump()
{
	while (!m_sList.empty())
	{
		string sLine = m_sList.front();
		m_sList.pop_front();
		if (fputs(sLine.c_str(), m_pFile) < 0)
			assert (false);
	}
	if (m_pFile)
	{
		fclose (m_pFile);
		m_pFile = 0;
	}
}

void CStringDump::Reset()
{
	// Cleanup if needed.
	if (m_pFile)
		fclose (m_pFile);
	m_sList.clear();
	m_Count = 0;

	string sLogFilename = m_sBaseFileName + GetDateTime('_', '_') + ".csv";
	m_pFile = fopen (sLogFilename.c_str(), "wb");
	if (!m_pFile)
	{
		printf ("Error opening file!\n");
		assert (false);
	}
}


string CStringDump::GetDateTime(char seperator, char timeSeperator)
{
	time_t t = time(0);   // get time now
    struct tm *pNow = localtime (&t);
	char buffer[128];
	sprintf (buffer, "%02d.%02d.%d%c%02d%c%02d%c%02d", pNow->tm_mday, (pNow->tm_mon + 1), (pNow->tm_year + 1900), seperator, pNow->tm_hour, timeSeperator, pNow->tm_min, timeSeperator, pNow->tm_sec);
	// printf ("Time = %s\n", buffer);
	return string(buffer);
}

