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

#include <iostream>
#include <stdio.h>
#include <string.h>
#include "LqrSMACObjectBroker.h"
#include "LqrSMACIObjectBroker-inline.h"
#include "LqrSMACObjectBroker-inline.h"
#include "LqrSMACStdOutLogger.h"
#include "SEProgram.h"
#include "SEProgramSettings.h"
#include "PayloadManagerClient.h"

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

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

	tzset();

	try
	{
		SEProgramSettings progSettings;
		progSettings.Load("SensorExample-config.xml");

		const SensorProgramSettings& settings = progSettings.GetSensorProgramSettings();

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

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

		SEProgram prog(broker, progSettings, logger);

		PortableServer::ServantBase_var theServer = 0;
		theServer = new ::POA_LiquidRobotics::SMAC::ISensorWithEvents_tie<SEProgram>(prog);

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

		prog.Initialize(serverRef.in());
		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;
}
