//---------------------------------------------------------------------------------
// <copyright file="PPPHostProgramSettings.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 PPPHostProgramSettings class, a serializable entity that
//   configures PPPHostProgram
// </summary>
//
// <owner>Mike Cookson</owner>
//---------------------------------------------------------------------------------

#include "PPPHostProgramSettings.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::EventLib;
using namespace LiquidRobotics::SMACFramework;

PPPHostProgramSettings::PPPHostProgramSettings()
: serverName("PPPHost")
//, serverKind("")
, waitForValidGPS(true)
, gpsEventSettings("GPSSample", "GPSSample", "LiquidR-SMC")
, useOriginalFilename(false)
{
}

PPPHostProgramSettings::PPPHostProgramSettings(const PPPHostProgramSettings& other)
: serverName(other.serverName)
, serverKind(other.serverKind)
, waitForValidGPS(other.waitForValidGPS)
, gpsEventSettings(other.gpsEventSettings)
, useOriginalFilename(other.useOriginalFilename)
, eventTransceiverSettings(other.eventTransceiverSettings)
, scpExecutorSettings(other.scpExecutorSettings)
, pmClientSettings(other.pmClientSettings)
{
}

PPPHostProgramSettings& PPPHostProgramSettings::operator=(const PPPHostProgramSettings& other)
{
	if (this != &other)
	{
		serverName = other.serverName;
		serverKind = other.serverKind;
		waitForValidGPS = other.waitForValidGPS;
		gpsEventSettings = other.gpsEventSettings;
		useOriginalFilename = other.useOriginalFilename;
		eventTransceiverSettings = other.eventTransceiverSettings;
		scpExecutorSettings = other.scpExecutorSettings;
		pmClientSettings = other.pmClientSettings;
	}

	return *this;
}

bool PPPHostProgramSettings::operator==(const PPPHostProgramSettings& other) const
{
	return !serverName.compare(other.serverName)
		&& !serverKind.compare(other.serverKind)
		&& (waitForValidGPS == other.waitForValidGPS)
		&& (gpsEventSettings == other.gpsEventSettings)
		&& (useOriginalFilename == other.useOriginalFilename)
		&& (eventTransceiverSettings == other.eventTransceiverSettings)
		&& (scpExecutorSettings == other.scpExecutorSettings)
		&& (pmClientSettings == other.pmClientSettings);
}

const string& PPPHostProgramSettings::GetServerName() const
{
	return serverName;
}

void PPPHostProgramSettings::SetServerName(const string& newValue)
{
	serverName = newValue;
}

const string& PPPHostProgramSettings::GetServerKind() const
{
	return serverKind;
}

void PPPHostProgramSettings::SetServerKind(const string& newValue)
{
	serverKind = newValue;
}

bool PPPHostProgramSettings::GetWaitForValidGPS() const
{
	return waitForValidGPS;
}

void PPPHostProgramSettings::SetWaitForValidGPS(bool newValue)
{
	waitForValidGPS = newValue;
}

const PPPHostProgramSettings::EventSettings& PPPHostProgramSettings::GPSEventSettings() const
{
	return gpsEventSettings;
}

void PPPHostProgramSettings::GPSEventSettings(EventSettings& newValue)
{
	gpsEventSettings = newValue;
}

const PPPHostProgramSettings::EventSettings& PPPHostProgramSettings::NewFileAvailableEventSettings() const
{
	return newFileAvailableEvent;
}

void PPPHostProgramSettings::NewFileAvailableEventSettings(EventSettings& newValue)
{
	newFileAvailableEvent = newValue;
}

const string& PPPHostProgramSettings::NewFileStorageRoot() const
{
	return newFileStorageRoot;
}

void PPPHostProgramSettings::NewFileStorageRoot(const string& newValue)
{
	newFileStorageRoot = newValue;
}

bool PPPHostProgramSettings::UseOriginalFilename() const
{
	return useOriginalFilename;
}

void PPPHostProgramSettings::UseOriginalFilename(bool newValue)
{
	useOriginalFilename = newValue;
}

const EventTransceiver::Settings& PPPHostProgramSettings::GetEventTransceiverSettings() const
{
	return eventTransceiverSettings;
}

void PPPHostProgramSettings::SetEventTransceiverSettings(const EventTransceiver::Settings& newValue)
{
	eventTransceiverSettings = newValue;
}

const PPPHostProgramSettings::SCPExecutorSettings& PPPHostProgramSettings::GetSCPExecutorSettings() const
{
	return scpExecutorSettings;
}

void PPPHostProgramSettings::SetSCPExecutorSettings(const SCPExecutorSettings& newValue)
{
	scpExecutorSettings = 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 PPPHostProgramSettings::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)
		{
			PPPHostProgramSettings 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 PPPHostProgramSettings::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

}

const PayloadManagerClientSettings& PPPHostProgramSettings::GetPMClientSettings() const
{
	return pmClientSettings;
}

void PPPHostProgramSettings::SetPMClientSettings(const PayloadManagerClientSettings& newValue)
{
	pmClientSettings = newValue;
}

ostream& operator<<(ostream& out, const PPPHostProgramSettings& settings)
{
	out << "serverName='" << settings.GetServerName() << "'"
		<< " serverKind='" << settings.GetServerKind() << "'"
		<< " waitForValidGPS=" << (settings.GetWaitForValidGPS() ? "true" : "false")
		<< " useOriginalFilename=" << (settings.UseOriginalFilename() ? "true" : "false")
		<< " gpsEventSettings={ " << settings.GPSEventSettings() << " }"
		<< " eventTransceiverSettings={ " << settings.GetEventTransceiverSettings() << " }"
		<< " scpExecutorSettings={ " << settings.GetSCPExecutorSettings() << " }"
		<< " pmClientSettings={ " << settings.GetPMClientSettings() << " }"
		;

	return out;
}
