using System;
using System.Collections.Generic;
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(0x58,"TOT")]
    public class LocalTimeOffsetDescriptor : TsDescriptor
    {
        public LocalTimeOffsetDescriptor(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            LocalTimeOffsets = new LocalTime[buffer.Length / 13];
            for (int i = 0; i < LocalTimeOffsets.Length; i++)
            {
                LocalTimeOffsets[i] = new LocalTime();
                LocalTimeOffsets[i].CountryCode = Encoding.ASCII.GetString(ms.ReadBytes(3));

                byte readUInt8 = ms.ReadUInt8();
                LocalTimeOffsets[i].CountryRegionId = (readUInt8 & 0xfc) >> 2;
                LocalTimeOffsets[i].LocalTimeOffsetPolarity = (readUInt8 & 0x01) != 0;
                LocalTimeOffsets[i].LocalTimeOffset = ReadTimeOffset(ms);

                DateTime? tmp = ms.ReadEtsiEn300468AnnexCDateTime();
                if (tmp == null)
                {
                    Valid = false;
                    return;
                }
                LocalTimeOffsets[i].TimeOfChange = tmp.Value;

                LocalTimeOffsets[i].NextTimeOffset = ReadTimeOffset(ms);
            }
            Valid = true;
        }

        public LocalTimeOffsetDescriptor(LocalTime[] offsets)
        {
	        this.LocalTimeOffsets = offsets;
        }

        private TimeSpan ReadTimeOffset(Stream s)
        {
            long a = s.ReadUInt8().UnpackBcd();
            long b = s.ReadUInt8().UnpackBcd();
            return new TimeSpan((int)a, (int)b, 0);
        }

        public LocalTime[] LocalTimeOffsets { get; }

        public class LocalTime
        {
            public string CountryCode { get; internal set; }
            public int CountryRegionId { get; internal set; }
            public bool LocalTimeOffsetPolarity { get; internal set; }
            public TimeSpan LocalTimeOffset { get; internal set; }
            public DateTime TimeOfChange { get; internal set; }
            public TimeSpan NextTimeOffset { get; internal set; }
        }

    }
}
