using System;

namespace Crysome.Common.Network;

public static class UdpTransport
{
	public const int HeaderSize = 13;

	public const int MaxFragmentSize = 60000;

	public static byte[] BuildFragment(uint sessionToken, byte packetTypeId, uint frameSeq, ushort fragIdx, ushort fragCount, byte[] payloadData, int payloadOffset, int payloadLength)
	{
		byte[] array = new byte[13 + payloadLength];
		int num = 0;
		Buffer.BlockCopy(BitConverter.GetBytes(sessionToken), 0, array, num, 4);
		num += 4;
		array[num++] = packetTypeId;
		Buffer.BlockCopy(BitConverter.GetBytes(frameSeq), 0, array, num, 4);
		num += 4;
		Buffer.BlockCopy(BitConverter.GetBytes(fragIdx), 0, array, num, 2);
		num += 2;
		Buffer.BlockCopy(BitConverter.GetBytes(fragCount), 0, array, num, 2);
		num += 2;
		Buffer.BlockCopy(payloadData, payloadOffset, array, num, payloadLength);
		return array;
	}

	public static bool ParseHeader(byte[] datagram, int length, out uint sessionToken, out byte packetTypeId, out uint frameSeq, out ushort fragIdx, out ushort fragCount, out int payloadOffset, out int payloadLength)
	{
		sessionToken = 0u;
		packetTypeId = 0;
		frameSeq = 0u;
		fragIdx = 0;
		fragCount = 0;
		payloadOffset = 0;
		payloadLength = 0;
		if (length < 13)
		{
			return false;
		}
		int num = 0;
		sessionToken = BitConverter.ToUInt32(datagram, num);
		num += 4;
		packetTypeId = datagram[num++];
		frameSeq = BitConverter.ToUInt32(datagram, num);
		num += 4;
		fragIdx = BitConverter.ToUInt16(datagram, num);
		num += 2;
		fragCount = BitConverter.ToUInt16(datagram, num);
		payloadLength = length - (payloadOffset = num + 2);
		return true;
	}
}
