//------------------------------------------------------------------------------
// <copyright file="SCPExecutorSettings.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 the SCPExecutorSettings class, a serializable entity that
//   contains the settings for the SCPExecutor class.
// </summary>
//
// <owner>Mike Cookson</owner>
//------------------------------------------------------------------------------

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

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

namespace LiquidRobotics {
namespace PPPHostLib {

inline void TestForBlank(const string& val, const string& msg1, const string msg2, bool invalidarg)
{
	string trimmed = val;
	boost::trim(trimmed);

	if (trimmed.empty())
	{
		stringstream msg;
		msg << msg1 << val << msg2 << " cannot be blank";

		if (invalidarg)
			throw invalid_argument(msg.str());
		else
			throw runtime_error(msg.str());
	}
}

template<typename T>
void MustBeInRange(const T& value, const T& minVal, const T& maxVal, const string& msg1, const string& msg2, bool invalidarg)
{
	if ((value < minVal) || (value > maxVal))
	{
		stringstream msg;
		msg << msg1 << value << msg2 << " must be between " << minVal << " and " << maxVal;

		if (invalidarg)
			throw invalid_argument(msg.str());
		else
			throw runtime_error(msg.str());
	}
}

SCPExecutorSettings::SCPExecutorSettings()
: callInInterval(300)
, scpVerb("scp somebody@10.10.10.10:thatfile .")
, runVerb("./thatfile")
, queueCapacity(100)
{
}

SCPExecutorSettings::SCPExecutorSettings(const SCPExecutorSettings& other)
: callInInterval(other.callInInterval)
, scpVerb(other.scpVerb)
, runVerb(other.runVerb)
, queueCapacity(other.queueCapacity)
, nextCallIntervalVerb(other.nextCallIntervalVerb)
, modemSerialNumberFilename(other.modemSerialNumberFilename)
, modemSimCardFilename(other.modemSimCardFilename)
, pppSettings(other.pppSettings)
{
}

SCPExecutorSettings& SCPExecutorSettings::operator=(const SCPExecutorSettings& other)
{
	if (this != &other)
	{
		callInInterval = other.callInInterval;
		scpVerb = other.scpVerb;
		runVerb = other.runVerb;
		queueCapacity = other.queueCapacity;
		nextCallIntervalVerb = other.nextCallIntervalVerb;
		modemSerialNumberFilename = other.modemSerialNumberFilename;
		modemSimCardFilename = other.modemSimCardFilename;
		pppSettings = other.pppSettings;
	}

	return *this;
}

bool SCPExecutorSettings::operator==(const SCPExecutorSettings& other) const
{
	return (this == &other)
		|| ((callInInterval == other.callInInterval)
		 && !scpVerb.compare(other.scpVerb)
		 && !runVerb.compare(other.runVerb)
		 && (queueCapacity == other.queueCapacity)
		 && !nextCallIntervalVerb.compare(other.nextCallIntervalVerb)
		 && !modemSerialNumberFilename.compare(other.modemSerialNumberFilename)
		 && !modemSimCardFilename.compare(other.modemSimCardFilename)
		 && (pppSettings == other.pppSettings));
}

float SCPExecutorSettings::GetCallInterval() const
{
	return callInInterval;
}

void SCPExecutorSettings::SetCallInterval(const float newValue)
{
	if (newValue > 0)
		MustBeInRange(newValue, 10.0f, 31.0f*24.0f*60.0f*60.0f, "Call-in interval (", ")", true);

	callInInterval = newValue;
}

const string& SCPExecutorSettings::GetSCPVerb() const
{
	return scpVerb;
}

void SCPExecutorSettings::SetSCPVerb(const string& newValue)
{
	TestForBlank(newValue, "SCP verb (", ")", true);
	scpVerb = newValue;
}

const string& SCPExecutorSettings::GetRunVerb() const
{
	return runVerb;
}

void SCPExecutorSettings::SetRunVerb(const string& newValue)
{
	TestForBlank(newValue, "Run verb (", ")", true);
	runVerb = newValue;
}

const PPPHostSettings& SCPExecutorSettings::GetPPPHostSettings() const
{
	return pppSettings;
}

void SCPExecutorSettings::SetPPPHostSettings(const PPPHostSettings& newValue)
{
	pppSettings = newValue;
}

unsigned SCPExecutorSettings::GetQueueCapacity() const
{
	return queueCapacity;
}

void SCPExecutorSettings::SetQueueCapacity(unsigned newValue)
{
	MustBeInRange(newValue, 10u, 10000u, "Queue capacity (", ")", true);
	queueCapacity = newValue;
}

const string& SCPExecutorSettings::GetNextCallIntervalVerb() const
{
	return nextCallIntervalVerb;
}

void SCPExecutorSettings::SetNextCallIntervalVerb(const string& newValue)
{
	nextCallIntervalVerb = newValue;
}

const string& SCPExecutorSettings::GetModemSerialNumberFilename() const
{
	return modemSerialNumberFilename;
}

void SCPExecutorSettings::SetNextCallIntervalFilename(const string& newValue)
{
	modemSerialNumberFilename = newValue;
}

const string& SCPExecutorSettings::GetModemSimCardFilename() const
{
	return modemSimCardFilename;
}

void SCPExecutorSettings::SetModemSimCardFilename(const string& newValue)
{
	modemSimCardFilename = newValue;
}

static const char* rootName = "rootlevel";

// Operations to deserialize from (Load) or serialize to (Save) a
// storage file; in the case of Load, if the file length is 0, the
// file is overwritten with some example data
void SCPExecutorSettings::Load(const string& fileName)
{
	// 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)
		{
			SCPExecutorSettings temp;
			temp.Save(fileName);
		}

		// 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 << "Loading " << typeid(*this).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, *this);			// read the root level item into the entity instance
	}
	else
	{
		// format the message content and throw the exception
		stringstream msg;
		msg << "Loading " << typeid(*this).name() << ": could not stat '" << fileName << "'"
		    << " (errno=" << errSave << " '" << GetErrorDescription(errSave) << "')";
		throw invalid_argument(msg.str());
	}
}

void SCPExecutorSettings::Save(const string& fileName)
{
	// 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 << "Saving " << typeid(*this).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, *this);			// write the root level using the entity
}

void SCPExecutorSettings::CheckValues() const
{
	if (callInInterval > 0)
		MustBeInRange(callInInterval, 10.0f, 31.0f*24.0f*60.0f*60.0f, "Call-in interval (", ")", false);

	TestForBlank(scpVerb, "SCP verb (", ")", false);
	TestForBlank(runVerb, "Run verb (", ")", false);
	MustBeInRange(queueCapacity, 10u, 10000u, "Queue capacity (", ")", false);
}

ostream& operator<<(ostream& out, const SCPExecutorSettings& settings)
{
	out << "callInInterval=" << settings.GetCallInterval()
		<< " scpVerb='" << settings.GetSCPVerb() << "'"
		<< " runVerb='" << settings.GetRunVerb() << "'"
		<< " queueCapacity=" << settings.GetQueueCapacity()
		<< " pppSettings={ " << settings.GetPPPHostSettings() << " }";

	return out;

}

}
}
