using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;

namespace AxCopilot.Views;

public class DockBarWindow : Window, IComponentConnector
{
	private struct MEMORYSTATUSEX
	{
		public uint dwLength;

		public uint dwMemoryLoad;

		public ulong ullTotalPhys;

		public ulong ullAvailPhys;

		public ulong ullTotalPageFile;

		public ulong ullAvailPageFile;

		public ulong ullTotalVirtual;

		public ulong ullAvailVirtual;

		public ulong ullAvailExtendedVirtual;
	}

	private DispatcherTimer? _timer;

	private PerformanceCounter? _cpuCounter;

	private TextBlock? _cpuText;

	private TextBlock? _ramText;

	private TextBlock? _clockText;

	private TextBox? _quickInput;

	private static readonly (string Key, string Icon, string Tooltip)[] AllItems = new(string, string, string)[8]
	{
		("launcher", "\ue721", "AX Commander"),
		("clipboard", "\ue77f", "클립보드 히스토리"),
		("capture", "\ue722", "화면 캡처"),
		("agent", "\ue8bd", "AX Agent"),
		("clock", "\ue823", "시계"),
		("cpu", "\ue950", "CPU"),
		("ram", "\ue7f4", "RAM"),
		("quickinput", "\ue8d3", "빠른 입력")
	};

	private DispatcherTimer? _glowTimer;

	private static readonly string[] FixedOrder = new string[8] { "launcher", "clipboard", "capture", "agent", "clock", "cpu", "ram", "quickinput" };

	internal Border RainbowGlowBorder;

	internal LinearGradientBrush RainbowBrush;

	internal Border DockBorder;

	internal StackPanel DockContent;

	private bool _contentLoaded;

	public Action<string>? OnQuickSearch { get; set; }

	public Action? OnCapture { get; set; }

	public Action? OnOpenAgent { get; set; }

	public Action<double, double>? OnPositionChanged { get; set; }

	public static IReadOnlyList<(string Key, string Icon, string Tooltip)> AvailableItems => AllItems;

	public DockBarWindow()
	{
		InitializeComponent();
		base.MouseLeftButtonDown += delegate(object _, MouseButtonEventArgs e)
		{
			if (e.LeftButton == MouseButtonState.Pressed)
			{
				try
				{
					DragMove();
				}
				catch
				{
				}
			}
		};
		base.LocationChanged += delegate
		{
			OnPositionChanged?.Invoke(base.Left, base.Top);
		};
		base.Loaded += delegate
		{
			PositionDock();
		};
		base.Closed += delegate
		{
			DispatcherTimer? timer = _timer;
			if (timer != null)
			{
				timer.Stop();
			}
			DispatcherTimer? glowTimer = _glowTimer;
			if (glowTimer != null)
			{
				glowTimer.Stop();
			}
			_cpuCounter?.Dispose();
		};
	}

	public void ApplySettings(double opacity, double left, double top, bool rainbowGlow)
	{
		base.Opacity = Math.Clamp(opacity, 0.3, 1.0);
		if (left >= 0.0 && top >= 0.0)
		{
			base.Left = left;
			base.Top = top;
		}
		else
		{
			((DispatcherObject)this).Dispatcher.BeginInvoke((DispatcherPriority)6, (Delegate)new Action(PositionDock));
		}
		if (rainbowGlow)
		{
			StartRainbowGlow();
		}
		else
		{
			StopRainbowGlow();
		}
	}

	private void StartRainbowGlow()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		RainbowGlowBorder.Visibility = Visibility.Visible;
		if (_glowTimer == null)
		{
			_glowTimer = new DispatcherTimer
			{
				Interval = TimeSpan.FromMilliseconds(50.0)
			};
		}
		double startAngle = 0.0;
		_glowTimer.Tick += delegate
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			startAngle += 2.0;
			if (startAngle >= 360.0)
			{
				startAngle -= 360.0;
			}
			double num = startAngle * Math.PI / 180.0;
			RainbowBrush.StartPoint = new Point(0.5 + 0.5 * Math.Cos(num), 0.5 + 0.5 * Math.Sin(num));
			RainbowBrush.EndPoint = new Point(0.5 - 0.5 * Math.Cos(num), 0.5 - 0.5 * Math.Sin(num));
		};
		_glowTimer.Start();
	}

	private void StopRainbowGlow()
	{
		DispatcherTimer? glowTimer = _glowTimer;
		if (glowTimer != null)
		{
			glowTimer.Stop();
		}
		RainbowGlowBorder.Visibility = Visibility.Collapsed;
	}

	public void BuildFromSettings(List<string> itemKeys)
	{
		//IL_080a: Unknown result type (might be due to invalid IL or missing references)
		//IL_080f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0829: Expected O, but got Unknown
		DockContent.Children.Clear();
		_cpuText = null;
		_ramText = null;
		_clockText = null;
		_quickInput = null;
		Brush foreground = (TryFindResource("PrimaryText") as Brush) ?? Brushes.White;
		Brush foreground2 = (TryFindResource("SecondaryText") as Brush) ?? Brushes.Gray;
		Brush brush = (TryFindResource("AccentColor") as Brush) ?? Brushes.CornflowerBlue;
		bool flag = false;
		bool flag2 = false;
		HashSet<string> enabledSet = new HashSet<string>(itemKeys, StringComparer.OrdinalIgnoreCase);
		foreach (string item in FixedOrder.Where((string k) => enabledSet.Contains(k)))
		{
			if (flag2)
			{
				AddSeparator();
			}
			flag2 = true;
			switch (item)
			{
			case "launcher":
				AddButton("\ue721", "AX Commander", foreground, delegate
				{
					OnQuickSearch?.Invoke("");
				});
				break;
			case "clipboard":
				AddButton("\ue77f", "클립보드", foreground, delegate
				{
					OnQuickSearch?.Invoke("#");
				});
				break;
			case "capture":
				AddButton("\ue722", "캡처", foreground, delegate
				{
					if (OnCapture != null)
					{
						OnCapture();
					}
					else
					{
						OnQuickSearch?.Invoke("cap");
					}
				});
				break;
			case "agent":
				AddButton("\ue8bd", "AI", foreground, delegate
				{
					if (OnOpenAgent != null)
					{
						OnOpenAgent();
					}
					else
					{
						OnQuickSearch?.Invoke("!");
					}
				});
				break;
			case "clock":
				_clockText = new TextBlock
				{
					Text = DateTime.Now.ToString("HH:mm"),
					FontSize = 12.0,
					FontWeight = FontWeights.SemiBold,
					Foreground = foreground,
					VerticalAlignment = VerticalAlignment.Center,
					Margin = new Thickness(6.0, 0.0, 6.0, 0.0)
				};
				DockContent.Children.Add(_clockText);
				flag = true;
				break;
			case "cpu":
			{
				StackPanel stackPanel3 = new StackPanel
				{
					Orientation = Orientation.Horizontal,
					VerticalAlignment = VerticalAlignment.Center
				};
				stackPanel3.Children.Add(new TextBlock
				{
					Text = "\ue950",
					FontFamily = new FontFamily("Segoe MDL2 Assets"),
					FontSize = 11.0,
					Foreground = brush,
					VerticalAlignment = VerticalAlignment.Center,
					Margin = new Thickness(0.0, 0.0, 3.0, 0.0)
				});
				_cpuText = new TextBlock
				{
					Text = "0%",
					FontSize = 11.0,
					Foreground = foreground2,
					VerticalAlignment = VerticalAlignment.Center,
					Width = 28.0,
					TextAlignment = TextAlignment.Right
				};
				stackPanel3.Children.Add(_cpuText);
				DockContent.Children.Add(stackPanel3);
				flag = true;
				if (_cpuCounter == null)
				{
					try
					{
						_cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
						_cpuCounter.NextValue();
					}
					catch
					{
					}
				}
				break;
			}
			case "ram":
			{
				StackPanel stackPanel2 = new StackPanel
				{
					Orientation = Orientation.Horizontal,
					VerticalAlignment = VerticalAlignment.Center
				};
				stackPanel2.Children.Add(new TextBlock
				{
					Text = "\ue7f4",
					FontFamily = new FontFamily("Segoe MDL2 Assets"),
					FontSize = 11.0,
					Foreground = brush,
					VerticalAlignment = VerticalAlignment.Center,
					Margin = new Thickness(0.0, 0.0, 3.0, 0.0)
				});
				_ramText = new TextBlock
				{
					Text = "0%",
					FontSize = 11.0,
					Foreground = foreground2,
					VerticalAlignment = VerticalAlignment.Center,
					Width = 28.0,
					TextAlignment = TextAlignment.Right
				};
				stackPanel2.Children.Add(_ramText);
				DockContent.Children.Add(stackPanel2);
				flag = true;
				break;
			}
			case "quickinput":
			{
				Border border = new Border();
				border.Background = (TryFindResource("ItemBackground") as Brush) ?? Brushes.Transparent;
				border.CornerRadius = new CornerRadius(8.0);
				border.Padding = new Thickness(8.0, 3.0, 8.0, 3.0);
				border.VerticalAlignment = VerticalAlignment.Center;
				Border border2 = border;
				StackPanel stackPanel = new StackPanel
				{
					Orientation = Orientation.Horizontal
				};
				stackPanel.Children.Add(new TextBlock
				{
					Text = "\ue721",
					FontFamily = new FontFamily("Segoe MDL2 Assets"),
					FontSize = 11.0,
					Foreground = brush,
					VerticalAlignment = VerticalAlignment.Center,
					Margin = new Thickness(0.0, 0.0, 5.0, 0.0)
				});
				_quickInput = new TextBox
				{
					Width = 100.0,
					FontSize = 11.0,
					Foreground = foreground,
					CaretBrush = brush,
					Background = Brushes.Transparent,
					BorderThickness = new Thickness(0.0),
					VerticalAlignment = VerticalAlignment.Center
				};
				_quickInput.KeyDown += QuickInput_KeyDown;
				stackPanel.Children.Add(_quickInput);
				border2.Child = stackPanel;
				DockContent.Children.Add(border2);
				break;
			}
			}
		}
		if (flag)
		{
			if (_timer == null)
			{
				_timer = new DispatcherTimer
				{
					Interval = TimeSpan.FromSeconds(1.0)
				};
			}
			_timer.Tick -= OnTick;
			_timer.Tick += OnTick;
			_timer.Start();
			OnTick(null, EventArgs.Empty);
		}
	}

	private void AddButton(string icon, string tooltip, Brush foreground, Action click)
	{
		Border border = new Border
		{
			Width = 30.0,
			Height = 30.0,
			CornerRadius = new CornerRadius(8.0),
			Background = new SolidColorBrush(Color.FromArgb(1, byte.MaxValue, byte.MaxValue, byte.MaxValue)),
			Cursor = Cursors.Hand,
			ToolTip = tooltip,
			Margin = new Thickness(2.0, 0.0, 2.0, 0.0)
		};
		border.Child = new TextBlock
		{
			Text = icon,
			FontFamily = new FontFamily("Segoe MDL2 Assets"),
			FontSize = 14.0,
			Foreground = foreground,
			HorizontalAlignment = HorizontalAlignment.Center,
			VerticalAlignment = VerticalAlignment.Center,
			IsHitTestVisible = false
		};
		border.MouseEnter += delegate(object s, MouseEventArgs _)
		{
			if (s is Border border2)
			{
				border2.Background = new SolidColorBrush(Color.FromArgb(34, byte.MaxValue, byte.MaxValue, byte.MaxValue));
			}
		};
		border.MouseLeave += delegate(object s, MouseEventArgs _)
		{
			if (s is Border border2)
			{
				border2.Background = new SolidColorBrush(Color.FromArgb(1, byte.MaxValue, byte.MaxValue, byte.MaxValue));
			}
		};
		border.MouseLeftButtonDown += delegate(object _, MouseButtonEventArgs e)
		{
			e.Handled = true;
			click();
		};
		DockContent.Children.Add(border);
	}

	private void AddSeparator()
	{
		DockContent.Children.Add(new Border
		{
			Width = 1.0,
			Height = 20.0,
			Margin = new Thickness(6.0, 0.0, 6.0, 0.0),
			Background = ((TryFindResource("SeparatorColor") as Brush) ?? Brushes.Gray)
		});
	}

	private void PositionDock()
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		Rect workArea = SystemParameters.WorkArea;
		base.Left = (((Rect)(ref workArea)).Width - base.ActualWidth) / 2.0 + ((Rect)(ref workArea)).Left;
		base.Top = ((Rect)(ref workArea)).Bottom - base.ActualHeight - 8.0;
	}

	private void OnTick(object? sender, EventArgs e)
	{
		if (_clockText != null)
		{
			_clockText.Text = DateTime.Now.ToString("HH:mm");
		}
		if (_cpuText != null)
		{
			try
			{
				_cpuText.Text = $"{_cpuCounter?.NextValue() ?? 0f:F0}%";
			}
			catch
			{
				_cpuText.Text = "-";
			}
		}
		if (_ramText != null)
		{
			try
			{
				MEMORYSTATUSEX lpBuffer = new MEMORYSTATUSEX
				{
					dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>()
				};
				_ramText.Text = (GlobalMemoryStatusEx(ref lpBuffer) ? $"{lpBuffer.dwMemoryLoad}%" : "-");
			}
			catch
			{
				_ramText.Text = "-";
			}
		}
	}

	[DllImport("kernel32.dll")]
	private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);

	private void QuickInput_KeyDown(object sender, KeyEventArgs e)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Invalid comparison between Unknown and I4
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Invalid comparison between Unknown and I4
		if ((int)e.Key == 6 && _quickInput != null && !string.IsNullOrWhiteSpace(_quickInput.Text))
		{
			OnQuickSearch?.Invoke(_quickInput.Text);
			_quickInput.Text = "";
			e.Handled = true;
		}
		else if ((int)e.Key == 13 && _quickInput != null)
		{
			_quickInput.Text = "";
			e.Handled = true;
		}
	}

	private void Window_KeyDown(object sender, KeyEventArgs e)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Invalid comparison between Unknown and I4
		if ((int)e.Key == 13)
		{
			Hide();
		}
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "10.0.5.0")]
	public void InitializeComponent()
	{
		if (!_contentLoaded)
		{
			_contentLoaded = true;
			Uri resourceLocator = new Uri("/AxCopilot;component/views/dockbarwindow.xaml", UriKind.Relative);
			Application.LoadComponent(this, resourceLocator);
		}
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "10.0.5.0")]
	[EditorBrowsable(EditorBrowsableState.Never)]
	void IComponentConnector.Connect(int connectionId, object target)
	{
		switch (connectionId)
		{
		case 1:
			((DockBarWindow)target).KeyDown += Window_KeyDown;
			break;
		case 2:
			RainbowGlowBorder = (Border)target;
			break;
		case 3:
			RainbowBrush = (LinearGradientBrush)target;
			break;
		case 4:
			DockBorder = (Border)target;
			break;
		case 5:
			DockContent = (StackPanel)target;
			break;
		default:
			_contentLoaded = true;
			break;
		}
	}
}
