using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InABox.DigitalMatter
{
    public class DMDataRequest : DMMessage
    {
        public List<DMRecord> _records = new();
        public override byte Type => 0x04;

        public DMRecord[] Records
        {
            get => _records.ToArray();
            set => _records = value.ToList();
        }

        protected override void DoDecode(IDMReadBuffer buffer)
        {
            _records.Clear();
            ushort bytestaken = 0;
            while (bytestaken < CheckSum)
            {
                var length = buffer.PeekUInt16(0);
                var record = new DMRecord();
                record.Decode(new DMPartialReadBuffer(buffer, 0, length));
                bytestaken += length;
                _records.Add(record);
            }
        }

        protected override void DoEncode(IDMWriteBuffer buffer)
        {
            foreach (var record in _records)
                record.Encode(buffer);
            buffer.InsertUInt16(0, buffer.BufferSize);
        }

        public override byte[] Dump()
        {
            return Encoding.UTF8.GetBytes($"(DataRequest):\n- {string.Join("\n- ", Records.Select(x => x.Dump()))}");
        }
    }
}