//-------------------------------------------------------------------------------------------------
// <copyright file="main.cpp" company="LiquidRobotics">
//  Copyright (c) Liquid Robotics Corporation, confidential and proprietary.  All rights reserved. 
// </copyright>
//
// <summary>
// 	main() function for LogListener
// </summary>
//
// <owner>Mike Cookson</owner>
//-------------------------------------------------------------------------------------------------

#include <iostream>
#include <string>
#include "LqrSMACFileSet.h"
#include "LqrSMACFileSetSettings.h"
#include "LqrSMACStdOutLogger.h"
#include "LqrSMACObjectBroker.h"
#include "LqrSMACIObjectBroker-inline.h"
#include "LqrSMACObjectBroker-inline.h"
#include <stdlib.h>
#include <boost/foreach.hpp>
#include "LqrSMACIdl.h"
#include "LogListenerProgram.h"
#include "LogListenerProgramSettings.h"
#include "PayloadManagerClient.h"

using namespace std;
using namespace LiquidRobotics::LogListener;
using namespace LiquidRobotics::EventLib;
using namespace LiquidRobotics::SMACFramework;
using namespace CORBA;

int main(int argc, char* argv[])
{
	int retcode = 0;

	tzset();

	try
	{
		LogListenerProgramSettings settings;
		settings.Load("LogListener-config.xml");

		const string serverName = settings.GetServerName();
		const string serverKind = settings.GetServerKind();
		StdOutLogger logger(settings.GetLoggerSettings());

		ObjectBroker broker(true);
		broker.Initialize(argc, argv);

		// Create Float Log File
		//FileSet floatLogFile(settings.GetFloatLogSettings());
		FileSetSettings::SizeType maxFiles = 1000;
		FileSetSettings::FileSizeType maxFileSize = 5000000;
		FileSetSettings floatLogFileSettings;
		floatLogFileSettings.SetMaxFileSize(maxFileSize);
		floatLogFileSettings.SetMaxFiles(maxFiles);
		floatLogFileSettings.SetPrefix("FLOAT_LOG");
		FileSet floatLogFile(floatLogFileSettings);

		LogListenerProgram prog(broker, settings, logger, floatLogFile);

		PortableServer::ServantBase_var theServer = 0;
		theServer = new ::POA_LiquidRobotics::SMAC::ICommandablePayloadDeviceWithEvents_tie<LogListenerProgram>(prog);

		Object_var serverRef = broker.AdvertizeInstance(theServer.in(), serverName.c_str(), serverKind.c_str());
		const PayloadManagerClientSettings& pmClientSettings = settings.GetPayloadManagerClientSettings();
		PayloadManagerClient::Ptr pmClient;
		pmClient.reset(new PayloadManagerClient(pmClientSettings, broker, prog));

		prog.Initialize(serverRef.in(), pmClient);
		pmClient->Register(serverRef.in());

		broker.ListenForRequests();
	}
	catch(CORBA::Exception& ex)
	{
		cerr << "Caught CORBA exception: " << DecodeCORBAException(ex) << endl;
		retcode = 1;
	}
	catch(exception& ex)
	{
		cerr << "Caught " << typeid(ex).name() << ": " << ex.what() << endl;
		retcode = 1;
	}

	return retcode;
}
