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

#include "PPPHostSettings.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());
	}
}

PPPHostSettings::PPPHostSettings()
: dialupTimeout(60)
, modemRegistrationTimeout(3*60)
, modemResponseTimeout(5)
, phoneNumber("sample phone number like")
, powerOffDelay(0)
, powerOnDelay(0)
, powerOffVerb("sample power off verb")
, powerOnVerb("sample power on verb")
, protocolDaemonVerb("sudo pppd /dev/ttyS99 19200 sample options")
, sendTries(5)
, queueCapacity(100)
//, spSettings(other.spSettings)
{
}

PPPHostSettings::PPPHostSettings(const PPPHostSettings& other)
: dialupTimeout(60)
, modemRegistrationTimeout(other.modemRegistrationTimeout)
, modemResponseTimeout(other.modemResponseTimeout)
, phoneNumber(other.phoneNumber)
, powerOffDelay(other.powerOffDelay)
, powerOnDelay(other.powerOnDelay)
, powerOffVerb(other.powerOffVerb)
, powerOnVerb(other.powerOnVerb)
, protocolDaemonVerb(other.protocolDaemonVerb)
, sendTries(other.sendTries)
, queueCapacity(other.queueCapacity)
, spSettings(other.spSettings)
{
}

PPPHostSettings::~PPPHostSettings()
{
}

PPPHostSettings& PPPHostSettings::operator=(const PPPHostSettings& other)
{
	if (this != &other)
	{
		dialupTimeout = other.dialupTimeout;
		modemResponseTimeout = other.modemResponseTimeout;
		modemRegistrationTimeout = other.modemRegistrationTimeout;
		phoneNumber = other.phoneNumber;
		powerOffDelay = other.powerOffDelay;
		powerOnDelay = other.powerOnDelay;
		powerOffVerb = other.powerOffVerb;
		powerOnVerb = other.powerOnVerb;
		protocolDaemonVerb = other.protocolDaemonVerb;
		sendTries = other.sendTries;
		queueCapacity = other.queueCapacity;
		spSettings = other.spSettings;
	}

	return *this;
}

bool PPPHostSettings::operator==(const PPPHostSettings& other) const
{
	return (dialupTimeout == other.dialupTimeout)
		&& (modemResponseTimeout == other.modemResponseTimeout)
		&& (modemRegistrationTimeout == other.modemRegistrationTimeout)
	    && !phoneNumber.compare(other.phoneNumber)
	    && (powerOffDelay == other.powerOffDelay)
		&& (powerOnDelay == other.powerOnDelay)
	    && !powerOffVerb.compare(other.powerOffVerb)
        && !powerOnVerb.compare(other.powerOnVerb)
        && !protocolDaemonVerb.compare(other.protocolDaemonVerb)
        && (sendTries == other.sendTries)
        && (queueCapacity == other.queueCapacity)
        && (spSettings == other.spSettings);
}

const string& PPPHostSettings::GetPhoneNumber() const
{
	return phoneNumber;
}

void PPPHostSettings::SetPhoneNumber(const string& newValue)
{
	//TestForBlank(newValue, "Phone number (", ")", true);
	phoneNumber = newValue;
}
const string& PPPHostSettings::GetPowerOffVerb() const
{
	return powerOffVerb;
}

void PPPHostSettings::SetPowerOffVerb(const string& newValue)
{
	powerOffVerb = newValue;
}

const string& PPPHostSettings::GetPowerOnVerb() const
{
	return powerOnVerb;
}

void PPPHostSettings::SetPowerOnVerb(const string& newValue)
{
	powerOnVerb = newValue;
}

float PPPHostSettings::GetPowerOffDelaySeconds() const
{
	return powerOffDelay;
}

void PPPHostSettings::SetPowerOffDelaySeconds(float newValue)
{
	MustBeInRange(newValue, 0.0f, 3600.0f, "Power off delay (", ")", false);
	powerOffDelay = newValue;
}

float PPPHostSettings::GetPowerOnDelaySeconds() const
{
	return powerOnDelay;
}

void PPPHostSettings::SetPowerOnDelaySeconds(float newValue)
{
	MustBeInRange(newValue, 0.0f, 3600.0f, "Power on delay (", ")", true);
	powerOnDelay = newValue;
}

const PPPHostSettings::SerialPortSettings& PPPHostSettings::GetSerialPortSettings() const
{
	return spSettings;
}

const float PPPHostSettings::GetModemResponseTimeoutSeconds() const
{
	return modemResponseTimeout;
}

void PPPHostSettings::SetModemResponseTimeoutSeconds(float newValue)
{
	MustBeInRange(newValue, 0.001f, 3600.0f, "Modem response timeout (", ")", true);
	modemResponseTimeout = newValue;
}

const float PPPHostSettings::GetModemRegistrationTimeoutSeconds() const
{
	return modemRegistrationTimeout;
}

void PPPHostSettings::SetModemRegistrationTimeoutSeconds(float newValue)
{
	MustBeInRange(newValue, 0.001f, 3600.0f, "Modem registration timeout (", ")", true);
	modemRegistrationTimeout = newValue;
}

void PPPHostSettings::SetSerialPortSettings(const SerialPortSettings& newValue)
{
	if (&spSettings != &newValue)
		spSettings = newValue;
}

const float PPPHostSettings::GetDialupTimeoutSeconds() const
{
	return dialupTimeout;
}

void PPPHostSettings::SetDialupTimeoutSeconds(float newValue)
{
	MustBeInRange(newValue, 0.001f, 3600.0f, "Dialup timeout (", ")", true);
	dialupTimeout = newValue;
}

const string& PPPHostSettings::GetProtocolDaemonVerb() const
{
	return protocolDaemonVerb;
}

void PPPHostSettings::SetProtocolDaemonVerb(const string& newValue)
{
	TestForBlank(newValue, "Protocol daemon verb (", ")", true);
	protocolDaemonVerb = newValue;
}

unsigned PPPHostSettings::GetSendTries() const
{
	return sendTries;
}

void PPPHostSettings::SetSendTries(unsigned newValue)
{
	MustBeInRange(newValue, 1u, 100u, "Send tries (", ")", true);
	sendTries = newValue;
}

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

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

void PPPHostSettings::CheckValues() const
{
	MustBeInRange(dialupTimeout, 0.001f, 3600.0f, "Serialized dialup timeout (", ")", false);
	MustBeInRange(modemRegistrationTimeout, 0.001f, 3600.0f, "Serialized modem registration timeout (", ")", false);
	MustBeInRange(modemResponseTimeout, 0.001f, 3600.0f, "Serialized modem response timeout (", ")", false);
	MustBeInRange(powerOffDelay, 0.0f, 3600.0f, "Serialized power off delay (", ")", false);
	MustBeInRange(powerOnDelay, 0.0f, 3600.0f, "Serialized power on delay (", ")", false);
	//TestForBlank(phoneNumber, "Serialized phone number (", ")", false);
	TestForBlank(protocolDaemonVerb, "Serialized protocol daemon verb (", ")", false);
	MustBeInRange(sendTries, 1u, 100u, "Send tries (", ")", false);
	MustBeInRange(queueCapacity, 10u, 1000u, "Queue capacity (", ")", false);
}

static const char* rootName = "rootlevel";

void PPPHostSettings::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)
		{
			PPPHostSettings 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 PPPHostSettings::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
}

ostream& operator<<(ostream& out, const PPPHostSettings& settings)
{
	out << "modemRegistrationTimeout=" << settings.GetModemRegistrationTimeoutSeconds()
		<< " modemResponseTimeout=" << settings.GetModemResponseTimeoutSeconds()
		<< " phoneNumber='" << settings.GetPhoneNumber() << "'"
        << " powerOffDelay='" << settings.GetPowerOffDelaySeconds() << "'"
        << " powerOnDelay='" << settings.GetPowerOnDelaySeconds() << "'"
	    << " powerOffVerb='" << settings.GetPowerOffVerb() << "'"
	    << " powerOnVerb='" << settings.GetPowerOnVerb() << "'"
	    << " protocolDaemonVerb='" << settings.GetProtocolDaemonVerb() << "'"
	    << " sendTries=" << settings.GetSendTries()
	    << " queueCapacity=" << settings.GetQueueCapacity()
	    << " spSettings={ " << settings.GetSerialPortSettings() << " }";

	return out;
}

}
}
