using ImGuiNET;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.Intrinsics.X86;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Skyscraper.Gps;

namespace SDL2Demo.Forms
{
	internal class GpsDisplay : IRenderable
	{
		private readonly IGpsReceiver gps;

		public GpsDisplay(IGpsReceiver gps)
		{
			this.gps = gps;
		}

		private string tableUuid;
		private PropertyInfo[] nmeaProps;
		private Vector2? setWindowSize;

		public bool RenderNmea { get; set; }
		public bool HasNmea { get; set; }

		public void Render()
		{
			if (this.tableUuid == null)
				tableUuid = Guid.NewGuid().ToString();

			if (setWindowSize.HasValue)
			{
				ImGui.SetNextWindowSize(setWindowSize.Value);
				setWindowSize = null;
			}

			if (ImGui.Begin("GPS", ImGuiWindowFlags.AlwaysVerticalScrollbar))
			{
				float f = ImGui.GetWindowWidth();
				if (f < 310)
				{
					setWindowSize = new Vector2(310, ImGui.GetWindowHeight());
				}
				if (gps.HasLock)
				{
					ImGui.BeginTable(tableUuid, 2);
					ImGui.TableNextRow();
					ImGui.TableSetColumnIndex(0);
					ImGui.Text("Location");

					ImGui.TableSetColumnIndex(1);
					GpsCoordinate gpsCoordinate = gps.Coordinate;
					ImGui.Text(String.Format("{0}, {1}", gpsCoordinate.Latitude, gpsCoordinate.Longitude));

					ImGui.Spacing();
					ImGui.Spacing();
					ImGui.Spacing();

					HasNmea = gps.ProvidesAdditionalNmeaData;
					if (RenderNmea)
					{
						AdditionalNmeaData nmeaData = gps.AdditionalNmeaData;
						if (nmeaData != null)
						{
							if (nmeaProps == null)
								nmeaProps = nmeaData.GetType().GetProperties();

							foreach (PropertyInfo propertyInfo in nmeaProps)
							{
								if (propertyInfo.PropertyType.IsArray)
									continue;

								if (propertyInfo.Name.Equals(nameof(nmeaData.Satellites)))
									continue;

								object? value = propertyInfo.GetValue(nmeaData);
								if (value != null)
								{
									ImGui.TableNextRow();
									ImGui.TableSetColumnIndex(0);
									ImGui.Text(propertyInfo.Name);

									ImGui.TableSetColumnIndex(1);
									ImGui.Text(value.ToString());
								}
							}
						}
					}

					ImGui.EndTable();
				}
				else
				{
					ImGui.Text("Waiting for lock...");
				}


				ImGui.End();
			}
		}
	}
}
