//------------------------------------------------------------------------------
// <copyright file="LqrSMACLoadSaveBoostXml.cpp" 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>
// 	Support functions for template-based serialization
// </summary>
//
// <owner>Mike Cookson</owner>
//------------------------------------------------------------------------------

#include "LqrSMACLoadSaveBoostXml.h"
#include <stdexcept>

using namespace std;

static string QuotedFileName(const string& fileName)
{
	stringstream fnstm;
	bool quoted = false;
	const char quoteChar = '\'';
	const char altQuoteChar = '\"';

	for (string::const_iterator it = fileName.begin(); it != fileName.end(); ++it)
	{
		const bool isQuote = (*it == quoteChar);

		if (isQuote == quoted)
		{
			fnstm << quoteChar;
			quoted = !quoted;
		}

		if (isQuote)
			fnstm << altQuoteChar << quoteChar << altQuoteChar;
		else
			fnstm << *it;
	}

	if (quoted)
		fnstm << quoteChar;

	string result = fnstm.str();
	return result;
}

namespace LiquidRobotics {
namespace SMACFramework {

std::string ReadEntireFileToString(const std::string& fileName, bool throwOnError)
{
	string result;

	try
	{
		ifstream ifs(fileName.c_str());
		result = ReadStreamToString(ifs, false, true);
	}
	catch(...)
	{
		if (throwOnError)
			throw;

		result.clear();
	}

	return result;
}

std::string ReadStreamToString(std::istream& is, bool rewind, bool throwOnError)
{
	try
	{
		is.clear();

		if (rewind)
			is.seekg(0, ios::beg);

		string result((istreambuf_iterator<char>(is)), istreambuf_iterator<char>());
		return result;
	}
	catch(...)
	{
		if (throwOnError)
			throw;
	}

	string emptyString;
	return emptyString;
}

bool CheckBoostXmlMD5(const std::string& fileName, bool throwOnError)
{
	const string fnQuoted = QuotedFileName(fileName);

	stringstream cmdLineStr;
	cmdLineStr << "md5sum -c " << fnQuoted << ".md5 2>&1 >/dev/null";

	const string cmdLine = cmdLineStr.str();
	const int status = system(cmdLine.c_str());
	const bool success = WIFEXITED(status) && !WEXITSTATUS(status);

	if (!success && throwOnError)
	{
		stringstream msg;
		msg << "MD5 check of " << fileName << " failed";

		throw runtime_error(msg.str());
	}

	return success;
}

SHARED_LIB_PUBLIC bool CreateBoostXmlMD5(const std::string& fileName, bool throwOnError)
{
	const string fnQuoted = QuotedFileName(fileName);

	stringstream cmdLineStr;
	cmdLineStr << "md5sum " << fnQuoted << " 2>/dev/null >" << fnQuoted << ".md5";

	const string cmdLine = cmdLineStr.str();
	const int status = system(cmdLine.c_str());
	const bool success = WIFEXITED(status) && !WEXITSTATUS(status);

	if (!success && throwOnError)
	{
		stringstream msg;
		msg << "MD5 could not be created for " << fileName;

		throw runtime_error(msg.str());
	}

	return success;
}

}
}

