namespace skyscraper8.GSE.GSE;

public class GseFragmentation
{
    public GseFragmentation(GsePacket child)
    {
        this.ProtocolType = child.ProtocolType.Value;
        this.Label = child.Label;
        AddFragement(child);
        this.TotalLength = child.TotalLength.Value;
        this.Crc32 = child.Crc32;
    }

    public uint Crc32 { get; set; }

    public ushort TotalLength { get; set; }

    private List<byte[]> fragments;

    public bool Validate()
    {
        //TODO: Implement proper CRC-32 checking here
	    return true;
    }

    public void AddFragement(GsePacket packet)
    {
        if (fragments == null)
            fragments = new List<byte[]>();
        
        fragments.Add(packet.GseDataBytes);
    }
    
    public GseLabel Label { get; private set; }

    public ushort ProtocolType { get; private set; }
    

    /// <summary>
    /// Assembles the payload
    /// </summary>
    /// <returns>The concatenated GSE Data Bytes of each packet.</returns>
    public byte[] GetGseDataBytes()
    {
        int totalLength = fragments.Select(x => x.Length).Sum();
        byte[] buffer = new byte[totalLength];
        int offset = 0;
        for (int i = 0; i < fragments.Count; i++)
        {
            Array.Copy(fragments[i],0,buffer,offset,fragments[i].Length);
            offset += fragments[i].Length;
        }
        return buffer;
    }
}