//-------------------------------------------------------------------------------------------------
// <copyright file="EventManagerSettings.cpp" company="LiquidRobotics">
//  Copyright (c) Liquid Robotics Corporation, confidential and proprietary.  All rights reserved. 
// </copyright>
//
// <summary>
//  Implementation of the EventManagerSettings class, which is a serializable entity
//  that holds the settings for the EventManager class.
// </summary>
//
// <owner>Mike Cookson</owner>
//-------------------------------------------------------------------------------------------------

#include "EventManagerSettings.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include "LqrSMACGetErrorDescription.h"

using namespace std;
using namespace boost::archive;
using namespace boost::serialization;
using namespace LiquidRobotics::SMACFramework;

namespace LiquidRobotics {
namespace EventManager {

EventManagerSettings::EventManagerSettings()
: eventManagerName("EventManager")
, maxSubscribers(50)
{
}

EventManagerSettings::~EventManagerSettings()
{
}

void EventManagerSettings::Load(const string& fileName)
{
	struct stat statBuf;
	int status = stat(fileName.c_str(), &statBuf);
	int errSave = errno;

	if (!status)
	{
		if (!statBuf.st_size)
		{
			EventManagerSettings temp;
			temp.Save(fileName);
		}

		ifstream ifs(fileName.c_str());

		if (!ifs.good())
		{
			stringstream msg;
			msg << "EventManagerSettings::Load: could not open '" << fileName << "' for read";
			throw invalid_argument(msg.str());
		}

		xml_iarchive ia(ifs);
		ia >> make_nvp("rootlevel", *this);
	}
	else
	{
		stringstream msg;

		msg << "EventManagerSettings::Load: could not stat '" << fileName << "'"
		    << " (" << GetErrorDescription(errSave) << ")";
		throw invalid_argument(msg.str());
	}
}

void EventManagerSettings::Save(const string& fileName)
{
	ofstream ofs(fileName.c_str());

	if (!ofs.good())
	{
		stringstream msg;
		msg << "EventManagerSettings::Save: could not open '" << fileName << "' for write";
		throw invalid_argument(msg.str());
	}

	xml_oarchive oa(ofs);
	oa << make_nvp("rootlevel", *this);
}


}
}
