using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.PMR.Common;
using Google.Protobuf;
using System.IO;
namespace Tango.PMR
{
///
/// Represents composition of message and a PMR message. aka Tango message.
///
///
public class TangoMessage : ITangoMessage where T : IMessage
{
///
/// Gets the container that will encapsulate the actual PMR message.
///
public MessageContainer Container { get; set; }
///
/// Gets or sets the message.
///
public T Message { get; set; }
///
/// Gets or sets the PMR message type.
///
public MessageType Type { get; set; }
///
/// Initializes a new instance of the class.
///
/// The message.
/// The type.
public TangoMessage(T message, MessageType type)
{
Message = message;
Type = type;
Container = new MessageContainer();
Container.Token = Guid.NewGuid().ToString();
Container.Type = Type;
}
///
/// Initializes a new instance of the class.
///
/// The message.
/// The type.
public TangoMessage(MessageContainer container, T message)
{
Message = message;
Container = container;
Type = container.Type;
}
///
/// Serializes the Tango message to byte array.
///
///
public byte[] ToBytes()
{
using (MemoryStream ms = new MemoryStream())
{
Message.WriteTo(ms);
ms.Position = 0;
Container.Data = ByteString.FromStream(ms);
}
using (MemoryStream ms = new MemoryStream())
{
Container.WriteTo(ms);
return ms.ToArray();
}
}
///
/// Serializes the Tango message to byte array representing a serialized JSON object of this Tango message.
///
///
public byte[] ToJsonBytes()
{
Container.Data = Message.ToByteString();
return Encoding.UTF8.GetBytes(Container.ToString());
}
///
/// Performs an implicit conversion from to .
///
/// The message.
///
/// The result of the conversion.
///
public static implicit operator TangoMessage(T message)
{
var tangoMessage = MessageFactory.CreateTangoMessage();
tangoMessage.Message = message;
return tangoMessage;
}
///
/// Performs an implicit conversion from to .
///
/// The instance.
///
/// The result of the conversion.
///
public static implicit operator T(TangoMessage instance)
{
return instance.Message;
}
///
/// Performs an implicit conversion from to .
///
/// The data.
///
/// The result of the conversion.
///
public static implicit operator TangoMessage(byte[] data)
{
return MessageFactory.ParseTangoMessage(data);
}
///
/// Returns a that represents this instance.
///
///
/// A that represents this instance.
///
public override string ToString()
{
return String.Format(@"Message Type: {0}
Token: {1}
Error: {2}
Message: {3}", Container.Type, Container.Token, Container.Error, Message.ToString());
}
}
}