using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Skyscraper.Plugins;

namespace skyscraper5.Dvb.Descriptors
{
	[SkyscraperPlugin]
	[TsDescriptor(0x45,"PMT")]
    [BannedTable("TSDT","BAT")]
    public class VbiDataDescriptor : TsDescriptor
    {
        public VbiDataDescriptor(byte[] buffer)
        {
            List<DataService> result = new List<DataService>();
            MemoryStream ms = new MemoryStream(buffer, false);
            while (ms.GetAvailableBytes() >= 2)
            {
                DataService child = new DataService();
                result.Add(child);

                child.DataServiceId = ms.ReadUInt8();
                int dataServiceLeng = ms.ReadUInt8();
                byte[] data = ms.ReadBytes(dataServiceLeng);
                if (child.DataServiceId == 0x01 || child.DataServiceId == 0x02 || child.DataServiceId == 0x04 || child.DataServiceId == 0x05 || child.DataServiceId == 0x06 || child.DataServiceId == 0x07)
                {
                    child.FieldParity = new bool[data.Length];
                    child.LineOffset = new int[data.Length];
                    for (int i = 0; i < data.Length; i++)
                    {
                        child.FieldParity[i] = (data[i] & 0x20) != 0;
                        child.LineOffset[i] = (data[i] & 0x1f);
                    }
                }
                else
                {
                    //Reserved? Don't care!
                }
            }

            VbiData = result.AsReadOnly();
        }

        public ReadOnlyCollection<DataService> VbiData { get; private set; }

        public class DataService
        {
            public byte DataServiceId { get; set; }

            public bool[] FieldParity { get; set; }

            public int[] LineOffset { get; set; }
        }
    }
}
