#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include "sock.h"
#include "consoleapp.h"
#include "timestamp.h"

#include "send.h"
#include "client.h"
#include "clientui.h"

void Usage()
{
	throw std::runtime_error("Invalid command line parameters");
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	std::string errorMessage;
	try
	{
		CTimestamp::Init();

		std::vector<std::string> arguments;
		std::istringstream argParser(lpCmdLine);
		typedef std::istream_iterator<std::string> ISIStr;
		std::copy( ISIStr(argParser), ISIStr(), back_inserter(arguments) );

		CWinSock winSock;

		if (arguments.size())
		{
			CConsoleApp consoleApp;
			if (arguments[0] == "send")
			{
				if (arguments.size() < 2)
					Usage();
				else
					DoSend(arguments[1]);
			}
			else if (arguments[0] == "client")
			{
				DoClient();
			}
		}
		else
		{
			DoClientUI();
		}
	}
	catch (std::exception& e)
	{
		std::ostringstream out;
		out << "Exception: " << e.what();
		errorMessage = out.str();
	}
	catch (...)
	{
		std::ostringstream out;
		out << "Unknown error";
		errorMessage = out.str();
	}

	if (!errorMessage.empty())
	{
		MessageBox( GetDesktopWindow(), errorMessage.c_str(), "Blow", MB_OK );
	}

	return errorMessage.size() != 0;
}
