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

namespace skyscraper5.src.InteractionChannel.Model2
{
	public class Fct2 : Validatable
	{
		public Fct2(MemoryStream ms)
		{
			byte frameTypeLoopCount = ms.ReadUInt8();
			frameTypeLoopCount++;
			FrameTypes = new Frame[frameTypeLoopCount];
			for (int i = 0; i < frameTypeLoopCount; i++)
			{
				FrameTypes[i] = new Frame();
				FrameTypes[i].FrameType = ms.ReadUInt8();
				FrameTypes[i].FrameDuration = ms.ReadUInt32BE();
				FrameTypes[i].TxFormatClass = ms.ReadUInt8();
				FrameTypes[i].BtuDuration = ms.ReadUInt24BE();
				FrameTypes[i].BtuCarrierBw = ms.ReadUInt24BE();
				FrameTypes[i].BtuSymbolRate = ms.ReadUInt24BE();
				FrameTypes[i].TimeUnitCount = ms.ReadUInt16BE();
				
				byte gridRepeatCount = ms.ReadUInt8();
				FrameTypes[i].GridFrequencyOffset = new uint[gridRepeatCount];
				for (int j = 0; j < gridRepeatCount; j++)
				{
					if (ms.GetAvailableBytes() < 2)
					{
						Valid = false;
						return;
					}
					FrameTypes[i].GridFrequencyOffset[j] = ms.ReadUInt24BE();
				}

				byte sectionLoopCount = ms.ReadUInt8();
				sectionLoopCount++;
				FrameTypes[i].SectionLoop = new SectionLoop[sectionLoopCount];
				for (int j = 0; j < sectionLoopCount; j++)
				{
					FrameTypes[i].SectionLoop[j] = new SectionLoop();
					FrameTypes[i].SectionLoop[j].DefaultTxType = ms.ReadUInt8();
					FrameTypes[i].SectionLoop[j].FixedAccessMethod = (ms.ReadUInt8() & 0x0f);
					FrameTypes[i].SectionLoop[j].RepeatCount = ms.ReadUInt16BE();
				}
			}

			Valid = true;
		}

		public Frame[] FrameTypes { get; private set; }
		public class Frame
		{
			public byte FrameType { get; set; }
			public uint FrameDuration { get; set; }
			public byte TxFormatClass { get; set; }
			public uint BtuDuration { get; set; }
			public uint BtuCarrierBw { get; set; }
			public uint BtuSymbolRate { get; set; }
			public ushort TimeUnitCount { get; set; }
			public uint[] GridFrequencyOffset { get; set; }
			public SectionLoop[] SectionLoop { get; set; }
		}

		public class SectionLoop
		{
			public byte DefaultTxType { get; set; }
			public int FixedAccessMethod { get; set; }
			public ushort RepeatCount { get; set; }
		}
	}
}
