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

namespace skyscraper8.Ietf.FLUTE
{
	internal class TimeHeaderExtension
	{
		private const double FACTOR = 1L << 32;
		private static readonly DateTime epoch = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc) + TimeSpan.FromSeconds(1L << 32);

		public TimeHeaderExtension(byte[] buffer) 
		{
			MemoryStream ms = new MemoryStream(buffer, false);
			byte v = ms.ReadUInt8();
			bool SctHiFlag = (v & 0x80) != 0;
			bool SctLowFlag = (v & 0x40) != 0;
			bool ErtFlag = (v & 0x20) != 0;
			bool SlcFlag = (v & 0x10) != 0;
			PiSpecificUse = ms.ReadUInt8();

			uint sctHi = 0;
			if (SctHiFlag)
				sctHi = ms.ReadUInt32BE();

			uint sctLow = 0;
			if (SctLowFlag)
				sctLow = ms.ReadUInt32BE();

			long sct = sctHi;
			sct <<= 32;
			sct += sctLow;
			this.Sct = epoch + TimeSpan.FromSeconds(sct / FACTOR);

			if (ErtFlag)
				Ert = ms.ReadUInt32BE();

			if (SlcFlag)
				Slc = ms.ReadUInt32BE();
		}

		public byte PiSpecificUse { get; }
		public DateTime Sct { get; }
		public uint Ert { get; }
		public uint Slc { get; }
	}
}
