#nullable enable
using System;
using System.Collections.Generic;
using System.Buffers.Binary;
namespace IGP.Multiplayer.Protocol
{
    internal static class IGPKcpFrameCodec
    {
        internal const int HeaderLength = 4;

        public static byte[] EncodeFrame(byte[] payload, IGPReliableTransportOptions? options = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            var resolvedOptions = options ?? IGPReliableTransportOptions.Default;
            if (payload.Length <= 0 || payload.Length > resolvedOptions.ReliableFrameMaxBytes)
            {
                throw new ArgumentOutOfRangeException(nameof(payload),
                    $"KCP frame payload exceeds KcpFrameMaxBytes={resolvedOptions.ReliableFrameMaxBytes}.");
            }

            var frame = new byte[HeaderLength + payload.Length];
            BinaryPrimitives.WriteUInt32BigEndian(frame.AsSpan(0, HeaderLength), (uint)payload.Length);
            Buffer.BlockCopy(payload, 0, frame, HeaderLength, payload.Length);
            return frame;
        }
    }

    internal sealed class IGPKcpFrameDecoder
    {
        private readonly IGPReliableTransportOptions options;
        private byte[] buffer = Array.Empty<byte>();
        private int readOffset;
        private int writeOffset;

        public IGPKcpFrameDecoder(IGPReliableTransportOptions? options = null)
        {
            this.options = options ?? IGPReliableTransportOptions.Default;
        }

        public IReadOnlyList<byte[]> Append(byte[] bytes, int offset, int count)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }

            if (offset < 0 || count < 0 || offset > bytes.Length - count)
            {
                throw new ArgumentOutOfRangeException(nameof(offset));
            }

            var frames = new List<byte[]>();
            while (count > 0)
            {
                if (writeOffset == buffer.Length)
                {
                    int remaining = writeOffset - readOffset;
                    if (readOffset > 0)
                    {
                        Buffer.BlockCopy(buffer, readOffset, buffer, 0, remaining);
                    }
                    else
                    {
                        int maximum = checked(options.ReliableFrameMaxBytes + IGPKcpFrameCodec.HeaderLength);
                        int capacity = (int)Math.Min(maximum, Math.Max(4096L, (long)buffer.Length * 2));
                        Array.Resize(ref buffer, capacity);
                    }
                    readOffset = 0;
                    writeOffset = remaining;
                }
                int copied = Math.Min(count, buffer.Length - writeOffset);
                Buffer.BlockCopy(bytes, offset, buffer, writeOffset, copied);
                writeOffset += copied;
                offset += copied;
                count -= copied;

                while (writeOffset - readOffset >= IGPKcpFrameCodec.HeaderLength)
                {
                    int payloadLength = (int)BinaryPrimitives.ReadUInt32BigEndian(buffer.AsSpan(readOffset, IGPKcpFrameCodec.HeaderLength));
                    if (payloadLength <= 0 || payloadLength > options.ReliableFrameMaxBytes)
                    {
                        Reset();
                        throw new InvalidOperationException(
                            $"KCP frame payload exceeds KcpFrameMaxBytes={options.ReliableFrameMaxBytes}.");
                    }
                    int totalLength = IGPKcpFrameCodec.HeaderLength + payloadLength;
                    if (writeOffset - readOffset < totalLength) break;
                    // Each returned payload has its own lifetime, independent of this connection.
                    var payload = new byte[payloadLength];
                    Buffer.BlockCopy(buffer, readOffset + IGPKcpFrameCodec.HeaderLength, payload, 0, payloadLength);
                    readOffset += totalLength;
                    frames.Add(payload);
                }
                if (readOffset == writeOffset) readOffset = writeOffset = 0;
            }

            return frames;
        }

        public void Reset()
        {
            buffer = Array.Empty<byte>();
            readOffset = writeOffset = 0;
        }
    }
}
