using System;
using System.Runtime.InteropServices;
using Decal.Interop.Net;

namespace Decal.Adapter.NetParser;

/// <summary>
/// Decal Message Factory Implementation
/// </summary>
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IMessageFactory))]
[ProgId("DecalAdapter.MessageFactory")]
[Guid("59D7815E-6716-4bd7-B264-69B6A9382701")]
public class MessageFactory : IMessageFactory
{
	/// <summary>
	/// Construct a new MessageFacytory instance
	/// </summary>
	public MessageFactory()
	{
	}

	/// <summary>
	/// Creates an IMessage2 instance from the provided raw packet data
	/// </summary>
	/// <param name="pData">Pointer to the raw packet bytes</param>
	/// <param name="size">Size of pData in bytes</param>
	/// <param name="outgoing">Packet direction</param>
	/// <returns>IMessage2 instance to navigate the packet</returns>
	IMessage2 IMessageFactory.CreateMessage(int pData, int size, bool outgoing)
	{
		if (pData != 0 && size != 0)
		{
			byte[] array = (byte[])Array.CreateInstance(typeof(byte), size);
			Marshal.Copy(new IntPtr(pData), array, 0, size);
			return new MessageWrapper(new Message(array, Message.GetParser(BitConverter.ToInt32(array, 0), outgoing ? MessageDirection.Outbound : MessageDirection.Inbound)));
		}
		return null;
	}
}
