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

namespace InABox.DigitalMatter
{
    public class DMBluetoothTagList : DMField
    {
        private List<DMBluetoothTagListItem> _items = new();
        public override byte Type => 0x1D;

        public DMBluetoothTagListItem[] Items
        {
            get => _items.ToArray();
            set => _items = value.ToList();
        }

        protected override void DoDecode(IDMReadBuffer buffer)
        {
            var bytestaken = 0;
            _items.Clear();
            while (buffer.BufferSize > 0 && bytestaken < Length)
            {
                var item = new DMBluetoothTagListItem();
                item.Decode(new DMPartialReadBuffer(buffer, 0, buffer.BufferSize));
                _items.Add(item);
                buffer.TakeBytes(item.DataLength + 3);
                bytestaken += item.DataLength + 3;
            }
        }

        protected override void DoEncode(IDMWriteBuffer buffer)
        {
            foreach (var tag in _items)
                tag.Encode(buffer);
        }

        public override string ToString()
        {
            return string.Join(", ", _items.Select(x => x.ToString()));
        }

        public override string Dump()
        {
            return $"Bluetooth Tags: [{string.Join(',', _items.Select(x => x.Tag))}]";
        }

        public override bool IsValid()
        {
            return _items.Any();
        }
    }
}