using System;
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()
        {
            _records.Clear();
            ushort bytestaken = 0;
            while (bytestaken < CheckSum)
            {
                var length = PeekUInt16(0);
                var record = new DMRecord();
                var buf = TakeBytes(length);
                bytestaken += length;
                record.Decode(buf);
                _records.Add(record);
            }
        }

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

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