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(0x76,"EIT")]
    [BannedTable("PMT")]
    public class ContentIdentifierDescriptor : TsDescriptor
    {
        public ContentIdentifierDescriptor(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            List<Crid> result = new List<Crid>();
            while (ms.GetAvailableBytes() > 0)
            {
                Crid child = new Crid();
                byte readUInt8 = ms.ReadUInt8();
                child.CridType = (CridType)((readUInt8 & 0xfc) >> 2);
                child.CridLocation = (CridLocation)(readUInt8 & 0x03);
                if ((int)child.CridLocation == 0x00)
                {
                    byte cridLength = ms.ReadUInt8();
                    child.CridBytes = ms.ReadBytes(cridLength);
                }

                if ((int)child.CridLocation == 0x01)
                {
                    child.CridRef = ms.ReadUInt16BE();
                }

                result.Add(child);
            }

            Crids = result.AsReadOnly();
        }

        public ReadOnlyCollection<Crid> Crids { get; private set; }

        public class Crid
        {
            public CridType CridType { get; set; }
            public CridLocation CridLocation { get; set; }
            public byte[] CridBytes { get; set; }

            public string CridBytesAsString
            {
                get
                {
                    return Encoding.ASCII.GetString(CridBytes);
                }
            }

            public ushort? CridRef { get; set; }
        }

        public enum CridType : byte
        {
            Undefined = 0,
            SelfSingle = 1,
            SelfSeries = 2,
            Recommendation = 3
        }

        public enum CridLocation : byte
        {
            WithinDescriptor = 0,
            CIT = 1
        }
    }
}
