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

namespace InABox.DigitalMatter
{
    public class DMRecord : DMObject
    {
        private List<DMField> _fields = new();

        public ushort Length { get; set; }

        public uint Sequence { get; set; }

        public uint TimeStamp { get; set; }

        public byte LogReason { get; set; }

        public DMField[] Fields
        {
            get => _fields.ToArray();
            set => _fields = value.ToList();
        }

        protected override void DoDecode()
        {
            //Logger.Send(LogType.Information, Thread.CurrentThread.ManagedThreadId.ToString(), String.Format("- Length: Size is [{0}]",BufferSize));
            Length = TakeUInt16();
            //Logger.Send(LogType.Information, Thread.CurrentThread.ManagedThreadId.ToString(), String.Format("- Sequence: Size is [{0}]", BufferSize));
            Sequence = TakeUInt32();
            //Logger.Send(LogType.Information, Thread.CurrentThread.ManagedThreadId.ToString(), String.Format("- TimeStamp: Size is [{0}]", BufferSize));
            TimeStamp = TakeUInt32();
            //Logger.Send(LogType.Information, Thread.CurrentThread.ManagedThreadId.ToString(), String.Format("- LogReason: Size is [{0}]", BufferSize));
            LogReason = TakeByte();

            ushort bytestaken = 0;
            _fields.Clear();
            while (bytestaken < Length && BufferSize > 0)
            {
                var fieldid = PeekByte(0);
                var fieldsize = PeekByte(1) == 255 ? PeekUInt16(1) : PeekByte(1);
                //Logger.Send(LogType.Information, Thread.CurrentThread.ManagedThreadId.ToString(), String.Format("{0}: Field ID is [{1}] Size is [{2}]", _fields.Count, fieldid, fieldsize));
                var field = DMFactory.ParseField(Buffer);
                _fields.Add(field);
                var bytestotake = field.Length > 255 ? field.Length + 3 : field.Length + 2;
                TakeBytes(bytestotake);
                bytestaken += (ushort)bytestotake;
            }
            //Logger.Send(LogType.Information, Thread.CurrentThread.ManagedThreadId.ToString(), String.Format("- Done!: Size is [{0}]", BufferSize));
        }

        protected override void DoEncode()
        {
            AddUInt32(Sequence);
            AddUInt32(TimeStamp);
            AddByte(LogReason);

            foreach (var field in _fields)
                AddBytes(field.Encode());

            InsertUInt16(0, BufferSize);
        }

        public string Dump()
        {
            return $"[{string.Join(',', _fields.Select(x => x.Dump()))}]";
        }
    }
}