/**
 * @file PCAPLiveCapture.cpp
 * @author Tomas Urban
 * @version 0.4
 * @date 23/07/2009
 */
#include <boost/tokenizer.hpp>
#include "PCAPLiveCapture.h"
#include "Logger/Logger.h"
#include <ctime>

PCAPLiveCapture::PCAPLiveCapture()
{
}

PCAPLiveCapture::~PCAPLiveCapture(void)
{
}

ECaptureInitResult PCAPLiveCapture::OpenDevice(const std::string sParams)
{
	CloseDevice();
	int nCounter = 1;
	const char * pszData = sParams.c_str();
	for (int i = 0; pszData[i]; i++)
		if (pszData[i] == ';')
			++nCounter;

	pcap_t ** tmpBuf = new pcap_t*[nCounter];
	
	std::string sTmp = sParams;	
	boost::char_separator<char> sep(";");
	boost::tokenizer<boost::char_separator<char> > tokens(sTmp, sep);
	nCounter = 0;
	ECaptureInitResult res = ECaptureInit_Successful;
	for(boost::tokenizer<boost::char_separator<char> >::iterator it = tokens.begin(); 
		it != tokens.end(); ++it)
	{
		pcap_t * pHandle = OpenPcapSource(it->c_str());
		if (pHandle)
			tmpBuf[nCounter++] = pHandle;
		else
		{
			std::string s = "Failed to open adapter \"";
			s += *it;
			s += "\" for packet capture.";
			Logger::Instance().LogWarning(s);
			res = ECaptureInit_PartiallySuccessful;
		}
	}

	bool bRes = true;
	if (nCounter > 0)
	{
		SetPcapHandles(tmpBuf, nCounter);
		std::string s = boost::lexical_cast<std::string>(nCounter);
		s += " adapter(s) available for packet capture";
		Logger::Instance().LogInfo(s);
		timeval timestamp;
		timestamp.tv_usec = 0;
#ifdef WIN32
		timestamp.tv_sec = static_cast<long>(time(0));
#else
		timestamp.tv_sec = time(0);
#endif
		SetStartPoint(timestamp);
	}
	else
	{
		Logger::Instance().LogError("No adapter available for packet capture");
		res = ECaptureInit_Failed;
	}
	delete tmpBuf;
	return res;
}

bool PCAPLiveCapture::SetCaptureFile(const std::string sFile)
{
	return InitCaptureFile(sFile);
}

