using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using Crysome.Server.Resources;
using Microsoft.Win32;
using Wpf.Ui.Controls;

namespace Crysome.Server;

public class LoginWindow : FluentWindow, IComponentConnector
{
	private const string LicenseKeysUrl = "https://crysome.net/key.txt";

	private const string BuyPageUrl = "https://t.me/CuriousCracks";

	private static readonly string SavedKeyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "license_key.dat");

	private static readonly HttpClient HttpClient = new HttpClient
	{
		Timeout = TimeSpan.FromSeconds(15L),
		DefaultRequestHeaders = { { "User-Agent", "Crysome-Server/1.0" } }
	};

	internal TextBox KeyBox;

	internal TextBlock ErrorText;

	internal Button BuyBtn;

	internal Button LoginBtn;

	internal Button ExitBtn;

	private bool _contentLoaded;

	public LoginWindow()
	{
		InitializeComponent();
		ApplyBackdrop();
		LoadSavedKey();
		KeyBox.KeyDown += delegate(object s, KeyEventArgs e)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			if ((int)e.Key == 6)
			{
				LoginButton_Click(s, e);
			}
		};
	}

	private void LoadSavedKey()
	{
		try
		{
			if (File.Exists(SavedKeyPath))
			{
				string text = File.ReadAllText(SavedKeyPath)?.Trim();
				if (!string.IsNullOrEmpty(text) && KeyBox != null)
				{
					KeyBox.Text = text;
				}
			}
		}
		catch
		{
		}
	}

	private void SaveKey(string key)
	{
		try
		{
			if (!string.IsNullOrWhiteSpace(key))
			{
				File.WriteAllText(SavedKeyPath, key.Trim());
			}
		}
		catch
		{
		}
	}

	private void ApplyBackdrop()
	{
		if (IsWindows11OrNewer())
		{
			((FluentWindow)this).ExtendsContentIntoTitleBar = true;
			((FluentWindow)this).WindowBackdropType = (WindowBackdropType)2;
			return;
		}
		((Control)this).Background = new SolidColorBrush(Color.FromRgb(32, 32, 32));
		if (((ContentControl)this).Content is Panel panel)
		{
			panel.Background = new SolidColorBrush(Color.FromRgb(32, 32, 32));
		}
	}

	private static bool IsWindows11OrNewer()
	{
		try
		{
			using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
			if (registryKey?.GetValue("CurrentBuild") is string s && int.TryParse(s, out var result))
			{
				return result >= 22000;
			}
		}
		catch
		{
		}
		return false;
	}

	private async void LoginButton_Click(object sender, RoutedEventArgs e)
	{
		((Window)this).DialogResult = true;
		((Window)this).Close();
	}

	private void ShowError()
	{
		ErrorText.Text = Strings.Login_ErrorMsg;
		ErrorText.Visibility = Visibility.Visible;
	}

	private static async Task<HashSet<string>> FetchValidKeysAsync()
	{
		string obj = await HttpClient.GetStringAsync("https://crysome.net/key.txt").ConfigureAwait(continueOnCapturedContext: false);
		HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
		string[] array = obj.Split(new string[3] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].Trim();
			if (text.Length > 0)
			{
				hashSet.Add(text);
			}
		}
		return hashSet;
	}

	private void BuyButton_Click(object sender, RoutedEventArgs e)
	{
		try
		{
			Process.Start(new ProcessStartInfo
			{
				FileName = "https://t.me/CuriousCracks",
				UseShellExecute = true
			});
		}
		catch (Exception ex)
		{
			MessageBox.Show(ex.Message, "Open URL", MessageBoxButton.OK, MessageBoxImage.Exclamation);
		}
	}

	private void ExitButton_Click(object sender, RoutedEventArgs e)
	{
		((Window)this).DialogResult = false;
		((Window)this).Close();
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "9.0.14.0")]
	public void InitializeComponent()
	{
		if (!_contentLoaded)
		{
			_contentLoaded = true;
			Uri resourceLocator = new Uri("/Crysome.Server;component/view/loginwindow.xaml", UriKind.Relative);
			Application.LoadComponent(this, resourceLocator);
		}
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "9.0.14.0")]
	[EditorBrowsable(EditorBrowsableState.Never)]
	void IComponentConnector.Connect(int connectionId, object target)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Expected O, but got Unknown
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Expected O, but got Unknown
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Expected O, but got Unknown
		switch (connectionId)
		{
		case 1:
			KeyBox = (TextBox)target;
			break;
		case 2:
			ErrorText = (TextBlock)target;
			break;
		case 3:
			BuyBtn = (Button)target;
			((ButtonBase)(object)BuyBtn).Click += BuyButton_Click;
			break;
		case 4:
			LoginBtn = (Button)target;
			((ButtonBase)(object)LoginBtn).Click += LoginButton_Click;
			break;
		case 5:
			ExitBtn = (Button)target;
			((ButtonBase)(object)ExitBtn).Click += ExitButton_Click;
			break;
		default:
			_contentLoaded = true;
			break;
		}
	}
}
