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

namespace skyscraper8.Skyscraper.Drawing
{
	public class IqChartData
	{
		private IqChartData()
		{
			IQ = new byte[256][];
			for (int i = 0; i < IQ.Length; i++)
			{
				IQ[i] = new byte[256];
			}

			packets = new List<byte[]>();
		}

		public byte[][] IQ;
		private List<byte[]> packets;
		private byte progress;

		public static IqChartData Create()
		{
			IqChartData child = new IqChartData();
			return child;
		}

		public static IqChartData LoadFrom(Stream indata)
		{
			if (indata.ReadUInt8() != 0x41)
				throw new ArgumentException("That stream isn't IQ Data!", nameof(indata));

			IqChartData result = null;
			while (indata.GetAvailableBytes() >= 4)
			{
				if (result == null)
					result = new IqChartData();

				int packSize = indata.ReadInt32LE();
				sbyte[] sbytes = indata.ReadSBytes(packSize);
				result.PushPacket(sbytes);
			}

			return result;
		}

		public bool IsComplete { get; private set; }


		public void PushPacket(sbyte[] buffer)
		{
			for (long l = 0; l < buffer.Length; l += 2)
			{
				byte i = (byte)(buffer[l] + sbyte.MaxValue);
				byte q = (byte)(buffer[l + 1] + sbyte.MaxValue);

				if (IQ[i][q] != 255)
				{
					IQ[i][q]++;
					if (IQ[i][q] > progress)
					{
						progress = IQ[i][q];
						Console.WriteLine(progress);
					}
				}
				else
				{
					IsComplete = true;
				}
			}

			byte[] writableBuffer = Array.ConvertAll(buffer, x => (byte)x);
			packets.Add(writableBuffer);
		}

		public void SaveTo(FileStream fs)
		{
			fs.WriteUInt8(0x41);
			foreach (byte[] packet in packets)
			{
				fs.WriteInt32LE(packet.Length);
				fs.Write(packet, 0, packet.Length);
			}
		}
	}
}
