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

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

            List<TargetRegion> _targetRegions = new List<TargetRegion>();
            while (ms.GetAvailableBytes() > 1)
            {
                byte readUInt8 = ms.ReadUInt8();
                bool countryCodeFlag = (readUInt8 & 0x04) != 0;
                int regionDepth = (readUInt8 & 0x03);
                
                TargetRegion childRegion = new TargetRegion();
                if (countryCodeFlag)
                {
                    childRegion.CountryCode = Encoding.ASCII.GetString(ms.ReadBytes(3));
                }

                if (regionDepth >= 1)
                {
                    childRegion.PrimaryRegionCode = ms.ReadUInt8();
                    if (regionDepth >= 2)
                    {
                        childRegion.SecondaryRegionCode = ms.ReadUInt8();
                        if (regionDepth == 3)
                        {
                            childRegion.TertiaryRegionCode = ms.ReadUInt16BE();
                        }
                    }
                }

                _targetRegions.Add(childRegion);
            }
            TargetRegions = _targetRegions;
        }

        public string CountryCode { get; private set; }

        public IReadOnlyList<TargetRegion> TargetRegions { get; private set; }

        public class TargetRegion
        {
            public string CountryCode { get; set; }
            public byte? PrimaryRegionCode { get; set; }
            public byte? SecondaryRegionCode { get; set; }
            public ushort? TertiaryRegionCode { get; set; }
        }
    }
}
