using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Dvb.DataBroadcasting.Biop.TapSelectors;
using skyscraper5.Skyscraper.IO;

namespace skyscraper5.Dvb.DataBroadcasting.Biop
{
    public class Tap
    {
        const bool CRASH_ON_PECULIAR_SELECTOR_TYPE = false;

        public Tap(MemoryStream ms)
        {
            ID = ms.ReadUInt16BE();
            Use = ms.ReadUInt16BE();
            AssociationTag = ms.ReadUInt16BE();

            byte selectorLength = ms.ReadUInt8();
            if (ms.GetAvailableBytes() < selectorLength)
                return;
            if (selectorLength >= 2)
            {
                ushort selectorType = ms.ReadUInt16BE();
                selectorLength -= 2;
                byte[] selectorDataBytes = ms.ReadBytes(selectorLength);

                if (selectorType == 0x01)
                    Selector = new SelectorType_0x01(selectorDataBytes);
                else
                {
                    if (CRASH_ON_PECULIAR_SELECTOR_TYPE)
                        throw new NotImplementedException(String.Format("{1} {0:X4}", selectorType, nameof(selectorType)));
                }
            }
        }

        public ushort AssociationTag { get; set; }

        public ushort Use { get; private set; }

        public ushort ID { get; private set; }

        public TapSelectors.SelectorType Selector { get; }
    }
}
