//------------------------------------------------------------------------------
// <copyright file="LqrSMACSerializationSupport.h" company="LiquidRobotics">
//
// Copyright (c) 2014 Liquid Robotics, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// This software is associated with a release.  Liquid Robotics makes no
// representation that the design, interfaces or component distribution will
// remain unchanged in future releases.
//
// </copyright>
//
// <summary>
//  Implements inline and template functions to support serialization of entity
//  classes
// </summary>
//
// <owner>Mike Cookson</owner>
//------------------------------------------------------------------------------

#ifndef __LQRSMACSERIALIZATIONSUPPORT_H__
#define __LQRSMACSERIALIZATIONSUPPORT_H__

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include "LqrSMACGetErrorDescription.h"

template<typename T>
void SaveToXmlArchive(const T& entity, const std::string& fileName, const char* rootName = "rootlevel")
{
	using namespace std;
	using namespace boost::archive;
	using namespace boost::serialization;

	// create a write stream to the archive
	ofstream ofs(fileName.c_str());

	// if the write stream is no good then throw invalid argument exception
	if (!ofs.good())
	{
		stringstream msg;
		msg << "SaveToXmlArchive(" << typeid(T).name() << ") could not open '" << fileName << "' for write";
		throw invalid_argument(msg.str());
	}

	xml_oarchive oa(ofs);						// construct an XML output archive based on the stream
	oa << make_nvp(rootName, entity);			// write the root level using the entity
}

template<typename T>
void SaveToXmlArchive(T& entity, const std::string& fileName, const char* rootName = "rootlevel")
{
	using namespace std;
	using namespace boost::archive;
	using namespace boost::serialization;

	// create a write stream to the archive
	ofstream ofs(fileName.c_str());

	// if the write stream is no good then throw invalid argument exception
	if (!ofs.good())
	{
		stringstream msg;
		msg << "SaveToXmlArchive(" << typeid(T).name() << ") could not open '" << fileName << "' for write";
		throw invalid_argument(msg.str());
	}

	xml_oarchive oa(ofs);						// construct an XML output archive based on the stream
	oa << make_nvp(rootName, entity);			// write the root level using the entity
}

template<typename T>
void LoadFromXmlArchive(T& entity, const std::string& fileName, const char* rootName = "rootlevel")
{
	using namespace std;
	using namespace boost::archive;
	using namespace boost::serialization;
	using namespace LiquidRobotics::SMACFramework;

	// get information about the archive
	struct stat statBuf;
	int status = stat(fileName.c_str(), &statBuf);
	int errSave = errno;

	// if the archive exists ...
	if (!status)
	{
		// if the file length is zero, then create a temporary instance and overwrite the archive
		if (!statBuf.st_size)
		{
			T temp;
			SaveToXmlArchive(temp, fileName, rootName);
		}

		// create a read stream from the archive
		ifstream ifs(fileName.c_str());

		// if the read stream is no good then throw invalid argument exception
		if (!ifs.good())
		{
			stringstream msg;
			msg << "LoadFromXmlArchive(" << typeid(T).name() << ") could not open '" << fileName << "' for read";
			throw invalid_argument(msg.str());
		}

		xml_iarchive ia(ifs);						// construct an XML input archive based on the stream
		ia >> make_nvp(rootName, entity);			// read the root level item into the entity instance
	}
	else
	{
		// format the message content and throw the exception
		stringstream msg;
		msg << "LoadFromXmlArchive(" << typeid(T).name() << ") could not stat '" << fileName << "'"
		    << " (errno=" << errSave << " '" << GetErrorDescription(errSave) << "')";
		throw invalid_argument(msg.str());
	}
}

#endif
