//------------------------------------------------------------------------------
// <copyright file="FCCMessage_Utilities.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 some utility functions relative to the Float C&C message
//   set types
// </summary>
//
// <owner>Mike Cookson</owner>
//------------------------------------------------------------------------------

#include "FCCMessage_Utilities.h"
#include "DoThrow.h"
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <time.h>

using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace boost::gregorian;

namespace LiquidRobotics {
namespace PayloadInterface {
namespace FCCMessage {

SHARED_LIB_PUBLIC void Convert(const DATE_TIME& input, ptime& output)
{
	bool useDefaultTime = false;

	try
	{
		if ((input.month < 1)
		 || (input.month > 12)
		 || (input.day < 1)
		 || (input.day > 31)
		 || (input.hour > 23)
		 || (input.minute > 59)
		 || (input.second > 59))

			useDefaultTime = true;

		else
		{
			date _date(2000+input.year, input.month-1, input.day);
			time_duration _time(input.hour, input.minute, input.second);

			output = ptime(_date, _time);
		}
	}
	catch(runtime_error& ex)
	{
		useDefaultTime = true;
	}

	if (useDefaultTime)
		output = ptime(date(2000, Jan, 1), time_duration(0,0,0));
}

SHARED_LIB_PUBLIC void Convert(const boost::posix_time::ptime& input, DATE_TIME& output)
{
	try
	{
		tm _tm = to_tm(input);

		output.year = (_tm.tm_year < 100) ? 0 : ((_tm.tm_year > 355) ? 255 : (_tm.tm_year-100));
		output.month = _tm.tm_mon+1;
		output.day = _tm.tm_mday;
		output.hour = _tm.tm_hour;
		output.minute = _tm.tm_min;
		output.second = _tm.tm_sec;
	}
	catch(runtime_error& ex)
	{
		output.year = 0;
		output.month = 0;
		output.day = 1;
		output.hour = 0;
		output.minute = 0;
		output.second = 0;
	}
}

SHARED_LIB_PUBLIC string ReportedToRealName(const REPORTED_NAME& reportedName)
{
	const string::size_type minLength = 11;
	const string::size_type baseNameLength = 8;
	const string::size_type extLength = 3;
	const string invalidchars = "./ \t";

	string reportedFileName = Stringize(reportedName);

	if (reportedFileName.length() < minLength)
		reportedFileName += string(minLength-reportedFileName.length(), ' ');

	string baseName = trim_right_copy(reportedFileName.substr(0, baseNameLength));
	string ext = trim_right_copy(reportedFileName.substr(baseNameLength,extLength));

	if ((baseName.find_first_of(invalidchars) != string::npos)
	 || (ext.find_first_of(invalidchars) != string::npos))
	{
		stringstream msg;
		msg << "ReportedToRealName: base (" << baseName << ") or extension (" << ext << ") of reportedFileName has invalid characters";

		DoThrow<invalid_argument>(__FILE__, __LINE__, msg.str());
	}

	stringstream stm;
	stm << baseName;

	if (ext.length())
		stm << "." << ext;

	string result = stm.str();

	if (result.length() == 1)
		DoThrow<invalid_argument>(__FILE__, __LINE__, "ReportedToRealName: reportedFileName is empty");

	return result;
}

SHARED_LIB_PUBLIC string ReportedStrToRealName(const string& reportedName)
{
	REPORTED_NAME reported = Unstringize(reportedName);
	string result = ReportedToRealName(reported);

	return result;
}

SHARED_LIB_PUBLIC REPORTED_NAME RealNameToReported(const string& realName)
{
	using namespace boost::filesystem;

	string baseName;
	string ext;

	if (!boost::equals(realName, "."))
	{
		path realNamePath = realName;
		path stemPath = realNamePath.stem();
		path extPath = realNamePath.extension();

		baseName = stemPath.string();
		ext = extPath.string();

		if (starts_with(ext, "."))
			ext.erase(ext.begin(), ext.begin()+1);
	}

	const string::size_type baseNameLength = 8;
	const string::size_type extLength = 3;
	const string invalidchars = "./ \t";

	if ((baseName.find_first_of(invalidchars) != string::npos)
	 || (ext.find_first_of(invalidchars) != string::npos))
	{
		stringstream msg;
		msg << "RealNameToReported: realName (" << realName << ") base (" << baseName << ") or extension (" << ext << ") of reportedFileName has invalid characters";

		DoThrow<invalid_argument>(__FILE__, __LINE__, msg.str());
	}

	if (baseName.length() < baseNameLength)
		baseName += string(baseNameLength-baseName.length(), ' ');
	else
		baseName.resize(baseNameLength);

	if (ext.length() < extLength)
		ext += string(extLength-ext.length(), ' ');
	else
		ext.resize(extLength);

	string resultAsStr = baseName + ext;

	REPORTED_NAME result;
	memcpy(result.paddedFileName, resultAsStr.c_str(), sizeof(result.paddedFileName));

	return result;
}

SHARED_LIB_PUBLIC std::string RealNameToReportedStr(const std::string& realName)
{
	REPORTED_NAME reported = RealNameToReported(realName);
	string result = Stringize(reported);

	return result;
}

SHARED_LIB_PUBLIC string Stringize(const REPORTED_NAME& reportedName)
{
	string result(reportedName.paddedFileName, reportedName.paddedFileName+sizeof(reportedName.paddedFileName));

	return result;
}

SHARED_LIB_PUBLIC REPORTED_NAME Unstringize(const string& reportedName)
{
	REPORTED_NAME result;
	size_t cpyLen = (reportedName.length() > sizeof(result)) ? sizeof(result) : reportedName.length();

	memcpy(result.paddedFileName, reportedName.c_str(), cpyLen);

	if (cpyLen < sizeof(result))
		memset(&result.paddedFileName[cpyLen], ' ', sizeof(result)-cpyLen);

	return result;
}

}
}
}
