﻿using ENetSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ENetSharp
{
    public static class Peer
    {
        /** Configures throttle parameter for a peer.
    Unreliable packets are dropped by ENet in response to the varying conditions
    of the Internet connection to the peer.  The throttle represents a probability
    that an unreliable packet should not be dropped and thus sent by ENet to the peer.
    The lowest mean round trip time from the sending of a reliable packet to the
    receipt of its acknowledgement is measured over an amount of time specified by
    the interval parameter in milliseconds.  If a measured round trip time happens to
    be significantly less than the mean round trip time measured over the interval, 
    then the throttle probability is increased to allow more traffic by an amount
    specified in the acceleration parameter, which is a ratio to the ENET_PEER_PACKET_THROTTLE_SCALE
    constant.  If a measured round trip time happens to be significantly greater than
    the mean round trip time measured over the interval, then the throttle probability
    is decreased to limit traffic by an amount specified in the deceleration parameter, which
    is a ratio to the ENET_PEER_PACKET_THROTTLE_SCALE constant.  When the throttle has
    a value of ENET_PEER_PACKET_THROTTLE_SCALE, on unreliable packets are dropped by 
    ENet, and so 100% of all unreliable packets will be sent.  When the throttle has a
    value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable
    packets will be sent.  Intermediate values for the throttle represent intermediate
    probabilities between 0% and 100% of unreliable packets being sent.  The bandwidth
    limits of the local and foreign hosts are taken into account to determine a 
    sensible limit for the throttle probability above which it should not raise even in
    the best of conditions.
    @param peer peer to configure 
    @param interval interval, in milliseconds, over which to measure lowest mean RTT; the default value is ENET_PEER_PACKET_THROTTLE_INTERVAL.
    @param acceleration rate at which to increase the throttle probability as mean RTT declines
    @param deceleration rate at which to decrease the throttle probability as mean RTT increases
*/

        public static void enet_peer_throttle_configure(ref ENetPeer peer, uint interval, uint acceleration, uint deceleration)
        {
            ENetProtocol command = new ENetProtocol();

            peer.packetThrottleInterval = interval;
            peer.packetThrottleAcceleration = acceleration;
            peer.packetThrottleDeceleration = deceleration;

            command.header.command = (int) ENetProtocolCommand.ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE |
                                     (int) ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
            command.header.channelID = 0xFF;

            command.throttleConfigure.packetThrottleInterval = (uint) Win32.ENET_HOST_TO_NET_32(interval);
            command.throttleConfigure.packetThrottleAcceleration = (uint) Win32.ENET_HOST_TO_NET_32(acceleration);
            command.throttleConfigure.packetThrottleDeceleration = (uint) Win32.ENET_HOST_TO_NET_32(deceleration);
            enet_peer_queue_outgoing_command(ref peer, ref command, null, 0, 0);
        }

        public static int enet_peer_throttle(ref ENetPeer peer, uint rtt)
        {
            if (peer.lastRoundTripTime <= peer.lastRoundTripTimeVariance)
            {
                peer.packetThrottle = peer.packetThrottleLimit;
            }
            else if (rtt < peer.lastRoundTripTime)
            {
                peer.packetThrottle += peer.packetThrottleAcceleration;

                if (peer.packetThrottle > peer.packetThrottleLimit)
                    peer.packetThrottle = peer.packetThrottleLimit;

                return 1;
            }
            else if (rtt > peer.lastRoundTripTime + 2*peer.lastRoundTripTimeVariance)
            {
                if (peer.packetThrottle > peer.packetThrottleDeceleration)
                    peer.packetThrottle -= peer.packetThrottleDeceleration;
                else
                    peer.packetThrottle = 0;

                return -1;
            }

            return 0;
        }

/** Queues a packet to be sent.
    @param peer destination for the packet
    @param channelID channel on which to send
    @param packet packet to send
    @retval 0 on success
    @retval < 0 on failure
*/

        public static int enet_peer_send(ref ENetPeer peer, int channelID, ref ENetPacket packet)
        {
            ENetChannel channel = peer.channels[channelID];
            ENetProtocol command = new ENetProtocol();
            int fragmentLength;

            if (peer.state != ENetPeerState.ENET_PEER_STATE_CONNECTED ||
                channelID >= peer.channelCount)
                return -1;

            fragmentLength = peer.mtu - Marshal.SizeOf<ENetProtocolHeader>() - Marshal.SizeOf<ENetProtocolSendFragment>();

            if (packet.dataLength > fragmentLength)
            {
                ushort startSequenceNumber = (ushort)Win32.ENET_HOST_TO_NET_16(channel.outgoingReliableSequenceNumber + 1);
                uint fragmentCount = (ushort)Win32.ENET_HOST_TO_NET_32((packet.dataLength + fragmentLength - 1)/fragmentLength),
                    fragmentNumber,
                    fragmentOffset;
                ENetList fragments = new ENetList();
                ENetOutgoingCommand fragment = new ENetOutgoingCommand();

                ENetListHelper.enet_list_clear(ref fragments);

                for (fragmentNumber = 0,
                    fragmentOffset = 0;
                    fragmentOffset < packet.dataLength;
                    ++ fragmentNumber,
                        fragmentOffset += (uint)fragmentLength)
                {
                    if (packet.dataLength - fragmentOffset < fragmentLength)
                        fragmentLength = packet.dataLength - (int)fragmentOffset;

                    fragment = new ENetOutgoingCommand
                    {
                        fragmentOffset = fragmentOffset,
                        fragmentLength = (ushort)fragmentLength,
                        packet = packet
                    };

                    fragment.command.header.command = (int)ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_FRAGMENT |
                                                      (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
                    fragment.command.header.channelID = channelID;
                    fragment.command.sendFragment.startSequenceNumber = startSequenceNumber;
                    fragment.command.sendFragment.dataLength = (ushort)Win32.ENET_HOST_TO_NET_16(fragmentLength);
                    fragment.command.sendFragment.fragmentCount = fragmentCount;
                    fragment.command.sendFragment.fragmentNumber = (uint)Win32.ENET_HOST_TO_NET_32(fragmentNumber);
                    fragment.command.sendFragment.totalLength = (uint)Win32.ENET_HOST_TO_NET_32(packet.dataLength);
                    fragment.command.sendFragment.fragmentOffset = (uint)Win32.ENET_NET_TO_HOST_32(fragmentOffset);

                    ENetListHelper.enet_list_insert(ref fragments, fragment);
                }

                packet.referenceCount += (int)fragmentNumber;
                while (!ENetListHelper.enet_list_empty(ref fragments))
                {
                    fragment = (ENetOutgoingCommand)ENetListHelper.enet_list_remove(ref fragments, ENetListHelper.enet_list_begin(ref fragments));

                    enet_peer_setup_outgoing_command(ref peer, ref fragment);
                }
                return 0;
            }

            command.header.channelID = channelID;

            if (packet.flags == ENetPacketFlag.ENET_PACKET_FLAG_RELIABLE)
            {
                command.header.command = (int)ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_RELIABLE | 
                    (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
                command.sendReliable.dataLength = (ushort)Win32.ENET_HOST_TO_NET_16(packet.dataLength);
            }
            else if (packet.flags == ENetPacketFlag.ENET_PACKET_FLAG_UNSEQUENCED)
            {
                command.header.command = (int)ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED |
                    (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
                command.sendUnsequenced.unsequencedGroup = (ushort)Win32.ENET_HOST_TO_NET_16(peer.outgoingUnsequencedGroup + 1);
                command.sendUnsequenced.dataLength = (ushort)Win32.ENET_HOST_TO_NET_16(packet.dataLength);
            }
            else if (channel.outgoingUnreliableSequenceNumber >= 0xFFFF)
            {
                command.header.command = (int)ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_RELIABLE | 
                    (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
                command.sendReliable.dataLength = (ushort)Win32.ENET_HOST_TO_NET_16(packet.dataLength);
            }
            else
            {
                command.header.command = (int)ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE;
                command.sendUnreliable.unreliableSequenceNumber =
                    (ushort)Win32.ENET_HOST_TO_NET_16(channel.outgoingUnreliableSequenceNumber + 1);
                command.sendUnreliable.dataLength = (ushort)Win32.ENET_HOST_TO_NET_16(packet.dataLength);
            }

            if (enet_peer_queue_outgoing_command(ref peer, ref command, packet, 0, (ushort)packet.dataLength) == null)
                return -1;

            return 0;
        }

/** Attempts to dequeue any incoming queued packet.
    @param peer peer to dequeue packets from
    @param channelID holds the channel ID of the channel the packet was received on success
    @returns a pointer to the packet, or NULL if there are no available incoming queued packets
*/

        public static ENetPacket enet_peer_receive(ref ENetPeer peer, ref int channelID)
        {
            ENetIncomingCommand incomingCommand;
            ENetPacket packet;

            if (ENetListHelper.enet_list_empty(ref peer.dispatchedCommands))
                return null;

            incomingCommand = (ENetIncomingCommand) ENetListHelper.enet_list_remove(ref peer.dispatchedCommands, ENetListHelper.enet_list_begin(ref peer.dispatchedCommands));

            channelID = incomingCommand.command.header.channelID;

            packet = incomingCommand.packet;

            -- packet.referenceCount;

            incomingCommand.fragments = null;

            incomingCommand = null;

            return packet;
        }

        public static void enet_peer_reset_outgoing_commands(ref ENetList queue)
        {
            ENetOutgoingCommand outgoingCommand;

            while (!ENetListHelper.enet_list_empty(ref queue))
            {
                outgoingCommand = (ENetOutgoingCommand)ENetListHelper.enet_list_remove(ref queue, ENetListHelper.enet_list_begin(ref queue));

                if (outgoingCommand.packet != null)
                {
                    -- outgoingCommand.packet.referenceCount;

                    if (outgoingCommand.packet.referenceCount == 0)
                        Packet.enet_packet_destroy(ref outgoingCommand.packet);
                }

                outgoingCommand = null;
            }
        }

        public static void enet_peer_reset_incoming_commands(ref ENetList queue)
        {
            ENetIncomingCommand incomingCommand;

            while (!ENetListHelper.enet_list_empty(ref queue))
            {
                incomingCommand = (ENetIncomingCommand)ENetListHelper.enet_list_remove(ref queue, ENetListHelper.enet_list_begin(ref queue));

                if (incomingCommand.packet != null)
                {
                    -- incomingCommand.packet.referenceCount;

                    if (incomingCommand.packet.referenceCount == 0)
                        Packet.enet_packet_destroy(ref incomingCommand.packet);
                }

                if (incomingCommand.fragments != null)
                    incomingCommand.fragments = null;

                incomingCommand = null;
            }
        }

        public static void enet_peer_reset_queues(ref ENetPeer peer)
        {
            ENetChannel channel;

            if (peer.needsDispatch != 0)
            {
                ENetListHelper.enet_list_remove(ref peer.dispatchList);

                peer.needsDispatch = 0;
            }

            //while (!enet_list_empty(&peer.acknowledgements))
            //    enet_free(enet_list_remove(enet_list_begin(&peer.acknowledgements)));
            ENetListHelper.enet_list_clear(ref peer.acknowledgements);

            enet_peer_reset_outgoing_commands(ref peer.sentReliableCommands);
            enet_peer_reset_outgoing_commands(ref peer.sentUnreliableCommands);
            enet_peer_reset_outgoing_commands(ref peer.outgoingReliableCommands);
            enet_peer_reset_outgoing_commands(ref peer.outgoingUnreliableCommands);
            enet_peer_reset_incoming_commands(ref peer.dispatchedCommands);

            if (peer.channels != null && peer.channelCount > 0)
            {
                for (var i = 0; i > peer.channelCount; i++)
                {
                    channel = peer.channels[i];
                    enet_peer_reset_incoming_commands(ref channel.incomingReliableCommands);
                    enet_peer_reset_incoming_commands(ref channel.incomingUnreliableCommands);
                    peer.channels[i] = channel;
                }

                peer.channels = null;
            }

            peer.channels = null;
            peer.channelCount = 0;
        }

/** Forcefully disconnects a peer.
    @param peer peer to forcefully disconnect
    @remarks The foreign host represented by the peer is not notified of the disconnection and will timeout
    on its connection to the local host.
*/

        public  static void enet_peer_reset(ref ENetPeer peer)
        {
            peer.outgoingPeerID = (ushort)ProtocolDefault.ENET_PROTOCOL_MAXIMUM_PEER_ID;
            peer.sessionID = 0;

            peer.state = ENetPeerState.ENET_PEER_STATE_DISCONNECTED;

            peer.incomingBandwidth = 0;
            peer.outgoingBandwidth = 0;
            peer.incomingBandwidthThrottleEpoch = 0;
            peer.outgoingBandwidthThrottleEpoch = 0;
            peer.incomingDataTotal = 0;
            peer.outgoingDataTotal = 0;
            peer.lastSendTime = 0;
            peer.lastReceiveTime = 0;
            peer.nextTimeout = 0;
            peer.earliestTimeout = 0;
            peer.packetLossEpoch = 0;
            peer.packetsSent = 0;
            peer.packetsLost = 0;
            peer.packetLoss = 0;
            peer.packetLossVariance = 0;
            peer.packetThrottle = (uint)ENetPeerHostDefaultSettings.ENET_PEER_DEFAULT_PACKET_THROTTLE;
            peer.packetThrottleLimit = (uint)ENetPeerHostDefaultSettings.ENET_PEER_PACKET_THROTTLE_SCALE;
            peer.packetThrottleCounter = 0;
            peer.packetThrottleEpoch = 0;
            peer.packetThrottleAcceleration = (uint)ENetPeerHostDefaultSettings.ENET_PEER_PACKET_THROTTLE_ACCELERATION;
            peer.packetThrottleDeceleration = (uint)ENetPeerHostDefaultSettings.ENET_PEER_PACKET_THROTTLE_DECELERATION;
            peer.packetThrottleInterval = (uint)ENetPeerHostDefaultSettings.ENET_PEER_PACKET_THROTTLE_INTERVAL;
            peer.lastRoundTripTime = (uint)ENetPeerHostDefaultSettings.ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
            peer.lowestRoundTripTime = (uint)ENetPeerHostDefaultSettings.ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
            peer.lastRoundTripTimeVariance = 0;
            peer.highestRoundTripTimeVariance = 0;
            peer.roundTripTime = (uint)ENetPeerHostDefaultSettings.ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
            peer.roundTripTimeVariance = 0;
            peer.mtu = (ushort)peer.host.mtu;
            peer.reliableDataInTransit = 0;
            peer.outgoingReliableSequenceNumber = 0;
            peer.windowSize = (uint)ProtocolDefault.ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
            peer.incomingUnsequencedGroup = 0;
            peer.outgoingUnsequencedGroup = 0;
            peer.disconnectData = 0;
            

            enet_peer_reset_queues(ref peer);
        }

/** Sends a ping request to a peer.
    @param peer destination for the ping request
    @remarks ping requests factor into the mean round trip time as designated by the 
    roundTripTime field in the ENetPeer structure.  Enet automatically pings all connected
    peers at regular intervals, however, this function may be called to ensure more
    frequent ping requests.
*/

        public static void enet_peer_ping(ref ENetPeer peer)
        {
            ENetProtocol command = new ENetProtocol();

            if (peer.state != ENetPeerState.ENET_PEER_STATE_CONNECTED)
                return;

            command.header.command = (int)ENetProtocolCommand.ENET_PROTOCOL_COMMAND_PING |
                (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
            command.header.channelID = 0xFF;

            enet_peer_queue_outgoing_command(ref peer, ref command, null, 0, 0);
        }

/** Force an immediate disconnection from a peer.
    @param peer peer to disconnect
    @param data data describing the disconnection
    @remarks No ENET_EVENT_DISCONNECT event will be generated. The foreign peer is not
    guarenteed to receive the disconnect notification, and is reset immediately upon
    return from this function.
*/

        public static void enet_peer_disconnect_now(ref ENetPeer peer, uint data)
        {
            ENetProtocol command = new ENetProtocol();

            if (peer.state == ENetPeerState.ENET_PEER_STATE_DISCONNECTED)
                return;

            if (peer.state != ENetPeerState.ENET_PEER_STATE_ZOMBIE &&
                peer.state != ENetPeerState.ENET_PEER_STATE_DISCONNECTING)
            {
                enet_peer_reset_queues(ref peer);

                command.header.command = (int)ENetProtocolCommand.ENET_PROTOCOL_COMMAND_DISCONNECT | 
                    (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
                command.header.channelID = 0xFF;
                command.disconnect.data = (uint)Win32.ENET_HOST_TO_NET_32(data);

                enet_peer_queue_outgoing_command(ref peer, ref command, null, 0, 0);

                Protocol.enet_host_flush(ref peer.host);
            }

            enet_peer_reset(ref peer);
        }

/** Request a disconnection from a peer.
    @param peer peer to request a disconnection
    @param data data describing the disconnection
    @remarks An ENET_EVENT_DISCONNECT event will be generated by enet_host_service()
    once the disconnection is complete.
*/

        public static void enet_peer_disconnect(ENetPeer peer, int data)
        {
            ENetProtocol command = new ENetProtocol();

            if (peer.state == ENetPeerState.ENET_PEER_STATE_DISCONNECTING ||
                peer.state == ENetPeerState.ENET_PEER_STATE_DISCONNECTED ||
                peer.state == ENetPeerState.ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT ||
                peer.state == ENetPeerState.ENET_PEER_STATE_ZOMBIE)
                return;

            enet_peer_reset_queues(ref peer);

            command.header.command = (int)ENetProtocolCommand.ENET_PROTOCOL_COMMAND_DISCONNECT;
            command.header.channelID = 0xFF;
            command.disconnect.data = (uint)Win32.ENET_HOST_TO_NET_32(data);

            if (peer.state == ENetPeerState.ENET_PEER_STATE_CONNECTED || peer.state == ENetPeerState.ENET_PEER_STATE_DISCONNECT_LATER)
                command.header.command |= (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
            else
                command.header.command |= (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;

            enet_peer_queue_outgoing_command(ref peer, ref command, null, 0, 0);

            if (peer.state == ENetPeerState.ENET_PEER_STATE_CONNECTED || peer.state == ENetPeerState.ENET_PEER_STATE_DISCONNECT_LATER)
                peer.state = ENetPeerState.ENET_PEER_STATE_DISCONNECTING;
            else
            {
                Protocol.enet_host_flush(ref peer.host);
                enet_peer_reset(ref peer);
            }
        }

/** Request a disconnection from a peer, but only after all queued outgoing packets are sent.
    @param peer peer to request a disconnection
    @param data data describing the disconnection
    @remarks An ENET_EVENT_DISCONNECT event will be generated by enet_host_service()
    once the disconnection is complete.
*/

        public static void enet_peer_disconnect_later(ref ENetPeer peer, uint data)
        {
            if ((peer.state == ENetPeerState.ENET_PEER_STATE_CONNECTED || peer.state == ENetPeerState.ENET_PEER_STATE_DISCONNECT_LATER) &&
                !(ENetListHelper.enet_list_empty(ref peer.outgoingReliableCommands) &&
                  ENetListHelper.enet_list_empty(ref peer.outgoingUnreliableCommands) &&
                  ENetListHelper.enet_list_empty(ref peer.sentReliableCommands)))
            {
                peer.state = ENetPeerState.ENET_PEER_STATE_DISCONNECT_LATER;
                peer.disconnectData = data;
            }
            else
                enet_peer_disconnect(peer, (int)data);
        }

        public static ENetAcknowledgement enet_peer_queue_acknowledgement(ref ENetPeer peer, ENetProtocol command, ushort sentTime)
        {
            ENetAcknowledgement acknowledgement;

            if (command.header.channelID < peer.channelCount)
            {
                ENetChannel channel = peer.channels[command.header.channelID];
                ushort reliableWindow = (ushort)(command.header.reliableSequenceNumber/(int)ENetPeerHostDefaultSettings.ENET_PEER_RELIABLE_WINDOW_SIZE),
                    currentWindow = (ushort)(channel.incomingReliableSequenceNumber/ (int)ENetPeerHostDefaultSettings.ENET_PEER_RELIABLE_WINDOW_SIZE);

                if (command.header.reliableSequenceNumber < channel.incomingReliableSequenceNumber)
                    reliableWindow += (ushort)ENetPeerHostDefaultSettings.ENET_PEER_RELIABLE_WINDOWS;

                if (reliableWindow >= currentWindow + (int)ENetPeerHostDefaultSettings.ENET_PEER_FREE_RELIABLE_WINDOWS - 1 &&
                    reliableWindow <= currentWindow + (int)ENetPeerHostDefaultSettings.ENET_PEER_FREE_RELIABLE_WINDOWS)
                    return null;
            }

            acknowledgement = new ENetAcknowledgement();

            peer.outgoingDataTotal += (uint)Marshal.SizeOf<ENetProtocolAcknowledge>();

            acknowledgement.sentTime = sentTime;
            acknowledgement.command = command;

            //TODO
            //ENetListHelper.enet_list_insert(ref acknowledgement, ENetListHelper.enet_list_end(ref peer.acknowledgements));

            return acknowledgement;
        }

        public static void enet_peer_setup_outgoing_command(ref ENetPeer peer, ref ENetOutgoingCommand outgoingCommand)
        {
            ENetChannel channel = peer.channels[outgoingCommand.command.header.channelID];

            peer.outgoingDataTotal += (uint)(Protocol.enet_protocol_command_size((ushort)outgoingCommand.command.header.command) +
                                      outgoingCommand.fragmentLength);

            if (outgoingCommand.command.header.channelID == 0xFF)
            {
                ++ peer.outgoingReliableSequenceNumber;

                outgoingCommand.reliableSequenceNumber = peer.outgoingReliableSequenceNumber;
                outgoingCommand.unreliableSequenceNumber = 0;
            }
            else if (outgoingCommand.command.header.command == (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE)
            {
                ++ channel.outgoingReliableSequenceNumber;
                channel.outgoingUnreliableSequenceNumber = 0;

                outgoingCommand.reliableSequenceNumber = channel.outgoingReliableSequenceNumber;
                outgoingCommand.unreliableSequenceNumber = 0;
            }
            else if (outgoingCommand.command.header.command == (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED)
            {
                ++ peer.outgoingUnsequencedGroup;

                outgoingCommand.reliableSequenceNumber = 0;
                outgoingCommand.unreliableSequenceNumber = 0;
            }
            else
            {
                ++ channel.outgoingUnreliableSequenceNumber;

                outgoingCommand.reliableSequenceNumber = channel.outgoingReliableSequenceNumber;
                outgoingCommand.unreliableSequenceNumber = channel.outgoingUnreliableSequenceNumber;
            }

            outgoingCommand.sendAttempts = 0;
            outgoingCommand.sentTime = 0;
            outgoingCommand.roundTripTimeout = 0;
            outgoingCommand.roundTripTimeoutLimit = 0;
            outgoingCommand.command.header.reliableSequenceNumber =
                (ushort)Win32.ENET_HOST_TO_NET_16(outgoingCommand.reliableSequenceNumber);

            if (outgoingCommand.command.header.command == (int)ENetProtocolFlag.ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE)
                ENetListHelper.enet_list_insert(ref peer.outgoingReliableCommands, outgoingCommand);
            else
                ENetListHelper.enet_list_insert(ref peer.outgoingUnreliableCommands, outgoingCommand);
        }

        public static ENetOutgoingCommand enet_peer_queue_outgoing_command(ref ENetPeer peer, ref ENetProtocol command,
            ENetPacket packet, uint offset, ushort length)
        {
            ENetOutgoingCommand outgoingCommand = new ENetOutgoingCommand
            {
                command = command,
                fragmentOffset = offset,
                fragmentLength = length,
                packet = packet
            };

            if (packet != null)
                ++ packet.referenceCount;

            enet_peer_setup_outgoing_command(ref peer, ref outgoingCommand);

            return outgoingCommand;
        }

        public static void enet_peer_dispatch_incoming_unreliable_commands(ref ENetPeer peer, ref ENetChannel channel)
        {
            ENetIncomingCommand currentCommand = null;

            foreach (var current in channel.incomingUnreliableCommands.data)
            {
                currentCommand = (ENetIncomingCommand)current;

                if ((currentCommand.command.header.command & (int) ENetProtocolCommand.ENET_PROTOCOL_COMMAND_MASK) !=
                    (int) ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE) continue;
                if (currentCommand.reliableSequenceNumber != channel.incomingReliableSequenceNumber)
                    break;

                channel.incomingUnreliableSequenceNumber = currentCommand.unreliableSequenceNumber;
            }

            if (currentCommand == ENetListHelper.enet_list_begin(ref channel.incomingUnreliableCommands))
                return;

            //TODO
            //ENetListHelper.enet_list_move(ENetListHelper.enet_list_end(ref peer.dispatchedCommands), 
            //ENetListHelper.enet_list_begin(ref channel.incomingUnreliableCommands),
            //ENetListHelper.enet_list_previous(ref currentCommand));

            if (peer.needsDispatch != 0)
            {
                ENetListHelper.enet_list_insert(ref peer.dispatchList, ENetListHelper.enet_list_end(ref peer.host.dispatchQueue));

                peer.needsDispatch = 1;
            }
        }

        public static void enet_peer_dispatch_incoming_reliable_commands(ref ENetPeer peer, ref ENetChannel channel)
        {
            ENetIncomingCommand currentCommand = null;

            foreach (var command in channel.incomingReliableCommands.data)
            {
                var incomingCommand = (ENetIncomingCommand)command;
                currentCommand = incomingCommand;

                if (incomingCommand.fragmentsRemaining > 0 ||
                    incomingCommand.reliableSequenceNumber != (ushort) (channel.incomingReliableSequenceNumber + 1))
                    break;

                channel.incomingReliableSequenceNumber = incomingCommand.reliableSequenceNumber;

                if (incomingCommand.fragmentCount > 0)
                    channel.incomingReliableSequenceNumber += (ushort)(incomingCommand.fragmentCount - 1);
            }

            if (currentCommand == ENetListHelper.enet_list_begin(ref channel.incomingReliableCommands))
                return;

            channel.incomingUnreliableSequenceNumber = 0;

            //TODO
            //enet_list_move(enet_list_end(&peer.dispatchedCommands), 
            //    enet_list_begin(&channel.incomingReliableCommands),
            //    enet_list_previous(currentCommand));

            if (peer.needsDispatch != 0)
            {
                ENetListHelper.enet_list_insert(ref peer.dispatchList, ENetListHelper.enet_list_end(ref peer.host.dispatchQueue));

                peer.needsDispatch = 1;
            }

            enet_peer_dispatch_incoming_unreliable_commands(ref peer, ref channel);
        }

        public static ENetIncomingCommand enet_peer_queue_incoming_command(ref ENetPeer peer, ref ENetProtocol command, ref ENetPacket packet, uint fragmentCount)
        {
            ENetIncomingCommand dummyCommand = null;

            ENetChannel channel = peer.channels[command.header.channelID];
            uint unreliableSequenceNumber = 0, reliableSequenceNumber = 0;
            ushort reliableWindow, currentWindow;
            ENetIncomingCommand incomingCommand;
            ENetList currentCommand = null;

            if (peer.state == ENetPeerState.ENET_PEER_STATE_DISCONNECT_LATER)
                goto freePacket;

            if (((ENetProtocolCommand)command.header.command & ENetProtocolCommand.ENET_PROTOCOL_COMMAND_MASK) !=
                ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED)
            {
                reliableSequenceNumber = command.header.reliableSequenceNumber;
                reliableWindow = (ushort)(reliableSequenceNumber/(int)ENetPeerHostDefaultSettings.ENET_PEER_RELIABLE_WINDOW_SIZE);
                currentWindow = (ushort)(channel.incomingReliableSequenceNumber/ (int)ENetPeerHostDefaultSettings.ENET_PEER_RELIABLE_WINDOW_SIZE);

                if (reliableSequenceNumber < channel.incomingReliableSequenceNumber)
                    reliableWindow += (int)ENetPeerHostDefaultSettings.ENET_PEER_RELIABLE_WINDOWS;

                if (reliableWindow < currentWindow ||
                    reliableWindow >= currentWindow + (int)ENetPeerHostDefaultSettings.ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
                    goto freePacket;
            }

            switch ((ENetProtocolCommand)command.header.command & ENetProtocolCommand.ENET_PROTOCOL_COMMAND_MASK)
            {
                case ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
                case ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
                    if (reliableSequenceNumber == channel.incomingReliableSequenceNumber)
                        goto freePacket;

                    foreach (var commands in channel.incomingReliableCommands.data)
                    {
                        incomingCommand = (ENetIncomingCommand)commands;

                        if (reliableSequenceNumber >= channel.incomingReliableSequenceNumber)
                        {
                            if (incomingCommand.reliableSequenceNumber < channel.incomingReliableSequenceNumber)
                                continue;
                        }
                        else if (incomingCommand.reliableSequenceNumber >= channel.incomingReliableSequenceNumber)
                            break;

                        if (incomingCommand.reliableSequenceNumber <= reliableSequenceNumber)
                        {
                            if (incomingCommand.reliableSequenceNumber < reliableSequenceNumber)
                                break;

                            goto freePacket;
                        }
                    }
                    break;

                case ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
                    unreliableSequenceNumber = (uint)Win32.ENET_NET_TO_HOST_16(command.sendUnreliable.unreliableSequenceNumber);

                    if (reliableSequenceNumber == channel.incomingReliableSequenceNumber &&
                        unreliableSequenceNumber <= channel.incomingUnreliableSequenceNumber)
                        goto freePacket;

                    foreach (var currentCommands in channel.incomingUnreliableCommands.data)
                    {
                        incomingCommand = (ENetIncomingCommand)currentCommands;

                        if (((ENetProtocolCommand)incomingCommand.command.header.command & ENetProtocolCommand.ENET_PROTOCOL_COMMAND_MASK) !=
                            ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE)
                            continue;

                        if (reliableSequenceNumber >= channel.incomingReliableSequenceNumber)
                        {
                            if (incomingCommand.reliableSequenceNumber < channel.incomingReliableSequenceNumber)
                                continue;
                        }
                        else if (incomingCommand.reliableSequenceNumber >= channel.incomingReliableSequenceNumber)
                            break;

                        if (incomingCommand.reliableSequenceNumber < reliableSequenceNumber)
                            break;

                        if (incomingCommand.reliableSequenceNumber > reliableSequenceNumber)
                            continue;

                        if (incomingCommand.unreliableSequenceNumber <= unreliableSequenceNumber)
                        {
                            if (incomingCommand.unreliableSequenceNumber < unreliableSequenceNumber)
                                break;

                            goto freePacket;
                        }
                    }
                    break;

                case ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
                    //currentCommand = ENetListHelper.enet_list_end(ref );
                    currentCommand = channel.incomingUnreliableCommands;
                    break;

                default:
                    goto freePacket;
            }

            incomingCommand = new ENetIncomingCommand();
            if (incomingCommand == null)
                goto notifyError;

            incomingCommand.reliableSequenceNumber = command.header.reliableSequenceNumber;
            incomingCommand.unreliableSequenceNumber = (ushort)(unreliableSequenceNumber & 0xFFFF);
            incomingCommand.command = command;
            incomingCommand.fragmentCount = fragmentCount;
            incomingCommand.fragmentsRemaining = fragmentCount;
            incomingCommand.packet = packet;
            incomingCommand.fragments = null;

            if (fragmentCount > 0)
            {
                incomingCommand.fragments = new uint[(fragmentCount + 31) / 32];
                if (incomingCommand.fragments == null)
                {
                    incomingCommand = null;

                    goto notifyError;
                }
                //(fragmentCount + 31)/32
                //memset(incomingCommand.fragments, 0, *sizeof(enet_uint32));
            }

            if (packet != null)
                ++ packet.referenceCount;

            //next
            ENetListHelper.enet_list_insert(ref currentCommand, incomingCommand);

            switch ((ENetProtocolCommand)command.header.command & ENetProtocolCommand.ENET_PROTOCOL_COMMAND_MASK)
            {
                case ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
                case ENetProtocolCommand.ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
                    enet_peer_dispatch_incoming_reliable_commands(ref peer, ref channel);
                    break;

                default:
                    enet_peer_dispatch_incoming_unreliable_commands(ref peer, ref channel);
                    break;
            }

            return incomingCommand;

            freePacket:
            if (fragmentCount > 0)
                goto notifyError;

            if (packet != null && packet.referenceCount == 0)
                Packet.enet_packet_destroy(ref packet);

            return dummyCommand;

            notifyError:
            if (packet != null && packet.referenceCount == 0)
                Packet.enet_packet_destroy(ref packet);

            return null;
        }
    }
}