/**
 * @file CapturedData.cpp
 * @author Tomas Urban
 * @version 0.3
 * @date 23/07/2009
 */
#include "TcpipServer.h"
#include "Logger/Logger.h"
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
	if (argc == 2 && strcmp(argv[1], "-help") == 0)
	{
		cout << "Usage: TrafficCapture.exe [-p port_number][-Linfo][-Lerr][-Lwarn][-Lcapt]\n";
		cout << "       [-Ldebug][-Lall][-Lnone]\n";
		cout << "-p port_number   Specifies the port for TCP/IP communication. 5501 is used\n";
		cout << "                 by default\n";
		cout << "-L*              Sets the log level. Log levels can be combined together.\n";
		cout << "                 The following log levels are available:\n";
		cout << "   -Linfo        Displays information messages\n";
		cout << "   -Lerr         Displays errors\n";
		cout << "   -Lwarn        Displays warnings\n";
		cout << "   -Ldebug       Displays debugging information\n";
		cout << "   -Lcapt        Displays capturing information\n";
		cout << "   -Lall         Displays all information\n";
		cout << "   -Lnone        No messages are displayed\n";
		return 0;
	}
	int nLogMode = 0;
	bool bLogModeSet = false;
	bool bError = false;
	Logger::Instance().SetLoggingMode(Logger::LOG_ERRORS);
	int nPort = TcpipServer::DEFAULT_PORT;
	for (int i = 1; i < argc; ++i)
	{
		bool bLog = false;
		char * pszArg = argv[i];
		if (strcmp(pszArg, "-p") == 0)
		{
			if (bError = i + 1 == argc)
				Logger::Instance().LogError("Port value missing");
			else
			{
				pszArg = argv[++i];
				nPort = atoi(pszArg);
			}
		}
		else if (bLog = strcmp(pszArg, "-Linfo") == 0)
			nLogMode |= Logger::LOG_INFO;
		else if (bLog = strcmp(pszArg, "-Lerr") == 0)
			nLogMode |= Logger::LOG_ERRORS;
		else if (bLog = strcmp(pszArg, "-Lwarn") == 0)
			nLogMode |= Logger::LOG_WARNINGS;
		else if (bLog = strcmp(pszArg, "-Lcapt") == 0)
			nLogMode |= Logger::LOG_CAPTURE;
		else if (bLog = strcmp(pszArg, "-Ldebug") == 0)
			nLogMode |= Logger::LOG_DEBUG | Logger::LOG_INFO;
		else if (bLog = strcmp(pszArg, "-Lall") == 0)
			nLogMode = Logger::LOG_ALL;
		else if (bLog = strcmp(pszArg, "-Lnone") == 0)
			nLogMode = Logger::LOG_NOTHING;
		else
		{
			bError = true;
			std::string s = "Unknown command line parameter \"";
			s += pszArg;
			s += "\"";
			Logger::Instance().LogError(s);
		}
		if (bLog)
			bLogModeSet = true;
	}

	if (bError)
		return 1;
	if (!bLogModeSet)
		nLogMode = Logger::LOG_INFO | Logger::LOG_ERRORS;
	Logger::Instance().SetLoggingMode(nLogMode);
	Logger::Instance().LogDebug("Command line parameters processed successfully");

#ifdef WIN32
	// Initialize Winsock.
	WSADATA wsaData;
	int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != NO_ERROR) 
	{
		Logger::Instance().LogError("Error at WSAStartup()\n");
		return 2;
	}
#endif
	TcpipServer::Instance().Run(nPort);
#ifdef WIN32
	WSACleanup();
#endif
	return 0;
}

