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.T2MI.Packets
{
	[SkyscraperPlugin]
	[T2MiPacketType(0x20)]
    public class _0x20_DvbT2Timestamp : T2MiPacket
    {
        public _0x20_DvbT2Timestamp(T2MIHeader header, byte[] buffer) : base(header, buffer)
        {
            if (buffer.Length < 10)
            {
                Valid = false;
                return;
            }
            MemoryStream ms = new MemoryStream(buffer, false);
            byte readUInt8 = ms.ReadUInt8();
            Bandwidth = (readUInt8 & 0x0f);

            SecondsSince2000 = ms.ReadUInt32BE();
            SecondsSince2000 <<= 8;
            SecondsSince2000 += ms.ReadUInt8();

            uint readUInt32Be = ms.ReadUInt32BE();
            Subseconds = (readUInt32Be & 0xffffffe0);
            SecondsSince2000 >>= 13;

            UTCoffset = (readUInt32Be & 0x0000001f);
            UTCoffset <<= 8;
            UTCoffset += ms.ReadUInt8();
            Valid = true;
        }

        public uint UTCoffset { get; private set; }

        public long Subseconds { get; private set; }

        public ulong SecondsSince2000 { get; private set; }

        public int Bandwidth { get; private set; }
        
        public DateTime ResolveTime()
        {
            DateTime dt = new DateTime(2000, 1, 1);
            
            ulong timeLeft = SecondsSince2000;
            while (timeLeft > 0)
            {
                ushort stepUp = (ushort)Math.Min(uint.MaxValue, timeLeft);
                if (stepUp == 0)
                    stepUp = 1;
                dt = dt.AddSeconds(stepUp);
                timeLeft -= stepUp;
            }
            
            return dt;
        }
    }
}
