//------------------------------------------------------------------------------
// <copyright file="StorageController_Config.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>
//   Implementation of StorageController::Config, a serializable entity inner
//   class of StorageController that stores its settings.
// </summary>
//
// <owner>Mike Cookson</owner>
//------------------------------------------------------------------------------

#include "StorageController.h"
#include "DoThrow.h"
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

using namespace std;
using namespace boost::archive;
using namespace boost::filesystem;
using namespace boost::serialization;

namespace LiquidRobotics {
namespace PayloadInterface {

IMPLEMENT_INNER_EXCEPTION(StorageController::Config, InvalidConfiguration, std::runtime_error)

static const char rootLevel[] = { "rootlevel" };
static const char className[] = { "StorageController::Config" };

StorageController::Config::Config()
: retainAllFiles(true)
, maxFilesToRetain(100)
{

}

StorageController::Config::Config(const string& _stateFileName, const string& _storageDirectoryName, unsigned _maxFilesToRetain, bool _retainAllFiles)
: stateFileName(_stateFileName)
, storageDirectory(_storageDirectoryName)
, retainAllFiles(_retainAllFiles)
, maxFilesToRetain(_maxFilesToRetain)
{
	VerifyConfig();
}

StorageController::Config::Config(const Config& right)
: stateFileName(right.stateFileName)
, storageDirectory(right.storageDirectory)
, retainAllFiles(right.retainAllFiles)
, maxFilesToRetain(right.maxFilesToRetain)
{
}

StorageController::Config& StorageController::Config::operator=(const Config& right)
{
	if (this != &right)
	{
		stateFileName = right.stateFileName;
		storageDirectory = right.storageDirectory;
		retainAllFiles = right.retainAllFiles;
		maxFilesToRetain = right.maxFilesToRetain;
	}

	return *this;
}

bool StorageController::Config::operator==(const Config& right) const
{
	return !stateFileName.compare(right.stateFileName)
	    && !storageDirectory.compare(right.storageDirectory)
	    && (retainAllFiles == right.retainAllFiles)
	    && (maxFilesToRetain == right.maxFilesToRetain);
}
void StorageController::Config::SetStateFileName(const char* newFileName)
{
	if (!newFileName)
		DoThrow<invalid_argument>(__FILE__, __LINE__, "newFileName is NULL");

	stateFileName.assign(newFileName);
}

void StorageController::Config::SetStateFileName(const string& newFileName)
{
	stateFileName.assign(newFileName);
}

void StorageController::Config::SetStorageDirectoryName(const char* newFileName)
{
	if (!newFileName)
		DoThrow<invalid_argument>(__FILE__, __LINE__, "newFileName is NULL");

	storageDirectory.assign(newFileName);
}

void StorageController::Config::SetStorageDirectoryName(const string& newFileName)
{
	storageDirectory.assign(newFileName);
}

void StorageController::Config::SetMaxFilesToRetain(unsigned newValue)
{
	maxFilesToRetain = newValue;
}

void StorageController::Config::SetRetainAllFiles(bool newValue)
{
	retainAllFiles = newValue;
}

void StorageController::Config::VerifyConfig() const
{
	if (!stateFileName.length())
		DoThrow<InvalidConfiguration>(__FILE__, __LINE__, "stateFileName is empty");

	if (!storageDirectory.length())
		DoThrow<InvalidConfiguration>(__FILE__, __LINE__, "storageDirectory is empty");

	stringstream stm;
	bool throwEx = false;
	path stateFileNamePath(stateFileName);

	try
	{
		stateFileNamePath.remove_filename();
	}
	catch(runtime_error& exc)
	{
		stm << "Parent not found for state filename string '" << stateFileName << "': " << exc.what();
		throwEx = true;
	}

	if (!throwEx)
	{
		if (!exists(stateFileNamePath))
		{
			stm << "Parent path '" << stateFileNamePath << "' does not exist for state filename '" << stateFileName << "'";
			throwEx = true;
		}
		else if (!is_directory(stateFileNamePath))
		{
			stm << "Parent path '" << stateFileNamePath << "' of state filename is not a directory";
			throwEx = true;
		}
		else
		{
			path scDirectoryPath(storageDirectory);

			if (!exists(scDirectoryPath))
			{
				stm << "Storage directory '" << scDirectoryPath << "' does not exist";
				throwEx = true;
			}

			else if (!is_directory(scDirectoryPath))
			{
				stm << "Storage directory '" << scDirectoryPath << "' is not a directory";
				throwEx = true;
			}
		}
	}

	if (throwEx)
	{
		string msg = stm.str();
		DoThrow<InvalidConfiguration>(__FILE__, __LINE__, msg);
	}
}

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

	if (!status)
	{
		if (!statBuf.st_size)
		{
			StorageController::Config temp;
			temp.Save(fileName);
		}

		ifstream ifs(fileName.c_str());

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

		xml_iarchive ia(ifs);
		ia >> make_nvp(rootLevel, *this);
	}
	else
	{
		char tempBuffer[256];
		strerror_r(errSave, tempBuffer, sizeof(tempBuffer));

		stringstream msg;

		msg << className << "::Load: could not stat '" << fileName << "'"
		    << " (errno=" << errSave << " '" << tempBuffer << "')";
		throw invalid_argument(msg.str());
	}
}

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

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

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

ostream& operator<<(ostream& stm, const StorageController::Config& config)
{
	stm << "stateFileName = '" << config.GetStateFileName() << "'";
	stm << " storageDirectory = '" << config.GetStorageDirectoryName() << "'";
	stm << " retainAllFiles = " << config.GetRetainAllFiles();
	stm << " maxFilesToRetain = " << config.GetMaxFilesToRetain();

	return stm;
}

}
}
