namespace TLVProtocal;

internal class TlvContentLayer(bool ConvertToBigEnd) : BaseFilter
{
    public override bool Receive(Data data)
    {
        if (data.RawData is null || data.RawData.Length <= 2)
            return false;

        if (data is not TlvData tlv)
            return false;

        ushort tag;
        if (ConvertToBigEnd)
        {
            byte[] lengthByte = new byte[2];
            Array.Copy(data.RawData, lengthByte, 2);
            Array.Reverse(lengthByte);
            tag = BitConverter.ToUInt16(lengthByte, 0);
        }
        else
            tag = BitConverter.ToUInt16(data.RawData, 0);

        byte[] content = new byte[data.RawData.Length - 2];
        Array.Copy(data.RawData, 2, content, 0, content.Length);

        if (ConvertToBigEnd)
            Array.Reverse(content);

        TlvData dataTLV = new(tag, content, data.Connection, data.DateTime);
        dataTLV.RequestID = tlv.RequestID;
        return base.Receive(dataTLV);
    }

    public override bool Send(Data data)
    {
        if (data is not TlvData tlv)
            return false;

        byte[] tag = BitConverter.GetBytes(tlv.Tag);
        byte[] content = tlv.RawData;

        if (ConvertToBigEnd)
        {
            Array.Reverse(tag);
            Array.Reverse(content);
        }

        List<byte> bytes = [];
        bytes.AddRange(tag);
        bytes.AddRange(content);

        TlvData tlvData = new(tlv.Tag, [.. bytes], data.Connection, data.DateTime);
        tlvData.RequestID = tlv.RequestID;
        return base.Send(tlvData);
    }
}
