//---------------------------------------------------------------------------------
// <copyright file="PayloadAddressableMessageService.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 a messaging service based on addresses and using payload
//	messages
// </summary>
//
// <owner>Mike Cookson</owner>
//---------------------------------------------------------------------------------

#include "PayloadAddressableMessageService.h"
#include "AddressedPacketEvent.h"
#include "FCCMessage.h"
#include "PayloadAddressableMessageServiceSettings.h"
#include "EventTransceiver.h"
#include "LqrSMACUptime.h"
#include "LqrSMACPayloadDescription.h"
#include <stdexcept>
#include <math.h>

using namespace std;
using namespace LiquidRobotics::SMACFramework;

namespace LiquidRobotics {
namespace PayloadInterface {

PayloadAddressableMessageService::PayloadAddressableMessageService(const PyldDesc& _senderDescription,
		const PayloadAddressableMessageServiceSettings& _settings, IObjectBroker& _broker, EventTransceiver& _eventTrans)
: senderDescription(_senderDescription)
, settings(_settings)
, broker(_broker)
, eventTrans(_eventTrans)
, firstTransaction(true)
, lastTransactionID(0)
{
}

static AddressedPacketEvent::NotifyType DeterminePacketType(ByteArray::Ptr data)
{
	if (!data || (data->size() == 0))
		throw invalid_argument("Packet type cannot be determined from an empty packet");

	AddressedPacketEvent::NotifyType result;

	switch((*data)[0])
	{

	case FCCMessage::RCV_CMD:
	case FCCMessage::RCV_SETTINGS:
	case FCCMessage::SND_TELEMETRY:
	case FCCMessage::SND_CONSOLE_OUTPUT:
	case FCCMessage::SND_NEW_FILE_AVAILABLE:
	case FCCMessage::SND_SINGLE_PAYLOAD_PACKET:
	case FCCMessage::SND_MULTI_PAYLOAD_PACKET:
	case FCCMessage::SND_SINGLE_PAYLOAD_PACKET_RECORD:
	case FCCMessage::SND_PAYLOAD_PACKET:
	case FCCMessage::SND_PAYLOAD_PACKET_91:
	case FCCMessage::SND_PAYLOAD_PACKET_RECORD:

		result = AddressedPacketEvent::NT_PRIMARY;
		break;

	case FCCMessage::SND_ENCRYPTED_PACKET:
	case FCCMessage::RCV_ENCRYPTED_COMMAND_PACKET:

		result = AddressedPacketEvent::NT_ENCRYPTED;
		break;

	case FCCMessage::ACK_WITH_SETTINGS_WAYPT:
	case FCCMessage::ACK_WITH_SETTINGS:
	case FCCMessage::ACK_WITH_ID:
	case FCCMessage::ACK_BASIC:
	case FCCMessage::ACK_WITH_POWER:
	case FCCMessage::ACK_WITH_RUDDER:
	case FCCMessage::ACK_WITH_DEBUG:
	case FCCMessage::ACK_WITH_SUB_HEADING:
	case FCCMessage::ACK_WITH_INTEGRAL:
	case FCCMessage::ACK_WITH_PID_PARAMS:
	case FCCMessage::ACK_WITH_ALL_PARAMS:
	case FCCMessage::ACK_WITH_READ_FILE:
	case FCCMessage::ACK_WITH_LIST_DETAILED:
	case FCCMessage::ACK_WITH_UNIQUE_ID:
	case FCCMessage::ACK_WITH_FILE_AT_DEST:
	case FCCMessage::NAK_CMD_BASIC:
	case FCCMessage::NAK_DATA_BASIC:
	case FCCMessage::NAK_DATA_ENUMERATED:
	case FCCMessage::NACK_CONSOLE_DATA:
	case FCCMessage::ACK_WITH_FILE_LIST:
	case FCCMessage::ACK_CONSOLE_DATA:
	case FCCMessage::ACK_SECURE_ON:
	default:

		result = AddressedPacketEvent::NT_SECONDARY;
		break;
	}

	return result;
}

PayloadAddressableMessageService::HandshakeTransactionID
PayloadAddressableMessageService::Transmit(BoardAddress remoteID, ByteArrayPtr data, bool requestAck)
{
	Semaphore::Lock semLock(sem);
	const AddressedPacketEvent::NotifyType notify = DeterminePacketType(data);
	PayloadAddressableMessageService::HandshakeTransactionID hsid =
		(PayloadAddressableMessageService::HandshakeTransactionID) ceil(100.0*GetSystemUpTimeSeconds());

	if (firstTransaction || (lastTransactionID < hsid))
	{
		lastTransactionID = hsid;
		firstTransaction = false;
	}
	else
		++lastTransactionID;

	PayloadAddressableMessageService::HandshakeTransactionID result =
		(PayloadAddressableMessageService::HandshakeTransactionID) lastTransactionID;
	semLock.unlock();

	AddressedPacketEvent pkt(settings.GetTransmitSettings(), broker, notify);
	pkt.SetSourceAddress(senderDescription.GetBoardID(), senderDescription.GetTaskID());
	pkt.SetDestAddress(remoteID);
	pkt.SetTransactionID(lastTransactionID);
	pkt.SetMessage(*data);
	eventTrans.TransmitEvent(pkt);
	return result;
}

}
}
