using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Echo.UserInterface.Backend;
using ScottPlot;
using ScottPlot.Plottables;
using skyscraper5.Dvb.Descriptors;
using skyscraper5.src.InteractionChannel.Model;
using Color = System.Drawing.Color;

namespace skyscraper8.UI.ImGui.Forms
{
	internal class SdlScottPlotWindowRfSpectrum : SdlScottPlotWindow
	{
		private DataLogger[] loggers;

		private Color[] colors = new Color[]
		{
			System.Drawing.Color.FromArgb(52, 152, 152),
			System.Drawing.Color.FromArgb(252, 52, 52),
			System.Drawing.Color.FromArgb(152, 52, 152),
			System.Drawing.Color.FromArgb(52, 52, 252),
		};

		public SdlScottPlotWindowRfSpectrum(ImGuiDevice imGuiDevice) 
			: base(imGuiDevice, new Plot(), 1000, 200, "RF Spectrum")
		{
			locakable = new object();
		}

		protected override void BeforeRender()
		{
			if (_queuedSamples == null)
				return;

			lock (locakable)
			{
				while (_queuedSamples.Count > 0)
				{
					Tuple<SatelliteDeliverySystemDescriptor.PolarizationEnum, int, double> value = _queuedSamples.Dequeue();
					if (loggers == null)
						loggers = new DataLogger[4];
					if (loggers[(int)value.Item1] == null)
					{
						loggers[(int)value.Item1] = _plot.Add.DataLogger();
						loggers[(int)value.Item1].LegendText = value.Item1.ToString();
						loggers[(int)value.Item1].Color = ScottPlot.Color.FromColor(colors[(int)value.Item1]);
					}

					loggers[(int)value.Item1].Add(value.Item2, value.Item3);
				}
			}
		}

		private Queue<Tuple<SatelliteDeliverySystemDescriptor.PolarizationEnum, int, double>> _queuedSamples;
		private object locakable;
		public void EnqueueSample(SatelliteDeliverySystemDescriptor.PolarizationEnum polarization, int frequency, double sample)
		{
			if (_queuedSamples == null)
				_queuedSamples = new Queue<Tuple<SatelliteDeliverySystemDescriptor.PolarizationEnum, int, double>>();

			lock (locakable)
			{
				_queuedSamples.Enqueue(new Tuple<SatelliteDeliverySystemDescriptor.PolarizationEnum, int, double>(polarization, frequency, sample));
			}
		}
	}
}
