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.Skyscraper.IO;
using skyscraper5.Skyscraper.Plugins;
using skyscraper5.Skyscraper.Text;

namespace skyscraper5.Dvb.Descriptors.Extension
{
	[SkyscraperPlugin]
	[ExtensionDescriptor(0x0A, "NIT","BAT")]
    public class TargetRegionNameDescriptor : Dvb.ExtensionDescriptor
    {
        public TargetRegionNameDescriptor(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            CountryCode = Encoding.ASCII.GetString(ms.ReadBytes(3));
            Iso639LanguageCode = Encoding.ASCII.GetString(ms.ReadBytes(3));

            List<TargetRegionName> regions = new List<TargetRegionName>();
            while (ms.GetAvailableBytes() > 2)
            {
                byte readUInt8 = ms.ReadUInt8();
                int regionDepth = (readUInt8 & 0xc0) >> 6;
                int regionNameLength = (readUInt8 & 0x3f);

                TargetRegionName childRegionName = new TargetRegionName();
                childRegionName.RegionName = En300468AnnexATextDecoder.GetInstance().Decode(ms.ReadBytes(regionNameLength));
                childRegionName.PrimaryRegionCode = ms.ReadUInt8();
                if (regionDepth >= 2)
                {
                    childRegionName.SecondaryRegionCode = ms.ReadUInt8();
                    if (regionDepth == 3)
                    {
                        childRegionName.TertiaryRegionCode = ms.ReadUInt16BE();
                    }
                }

                regions.Add(childRegionName);

            }
            Regions = regions.AsReadOnly();
        }

        public string Iso639LanguageCode { get; set; }

        public string CountryCode { get; set; }

        public IReadOnlyList<TargetRegionName> Regions { get; private set; }

        public class TargetRegionName
        {
            public string RegionName { get; internal set; }
            public byte PrimaryRegionCode { get; set; }
            public byte? SecondaryRegionCode { get; set; }
            public ushort? TertiaryRegionCode { get; set; }
        }
    }
}
