using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Ietf.Rfc971;

namespace skyscraper5.Skyscraper
{
    internal class IpPacketFinder
    {
        public static byte[] LookForIpPacket(byte[] gsPacket, int searchDepth = 16)
        {
            byte[] ipBuffer = new byte[20];

            for (int i = 1; i < searchDepth; i++)
            {
                int v4HeaderEnd = i + 20;
                if (v4HeaderEnd > gsPacket.Length)
                    return null;

                if (gsPacket[i] == 0x45)
                {
                    Array.Copy(gsPacket, i, ipBuffer, 0, ipBuffer.Length);
                    InternetHeader ipv4 = new InternetHeader(ipBuffer);
                    if (!ipv4.ChecksumValid)
                        continue;
                    int payloadStart = i + ipBuffer.Length;
                    int payloadEnd = i + ipv4.TotalLength;
                    if (payloadEnd > gsPacket.Length)
                        return null;
                    int packetLength = payloadEnd - i;

                    byte[] finalPacket = new byte[packetLength];
                    Array.Copy(gsPacket, i, finalPacket, 0, packetLength);
                    return finalPacket;
                }
            }

            return null;
        }
    }
}
