using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using Crysome.Server.Resources;
using Crysome.Server.View;

namespace Crysome.Server;

public class App : Application
{
	private bool _contentLoaded;

	private void Application_Startup(object sender, StartupEventArgs e)
	{
		base.ShutdownMode = ShutdownMode.OnExplicitShutdown;
		try
		{
			LanguageWindow languageWindow = new LanguageWindow();
			if (((Window)(object)languageWindow).ShowDialog() != true)
			{
				Shutdown();
				return;
			}
			ApplyCulture(languageWindow.SelectedCultureTag);
		}
		catch (Exception ex)
		{
			DumpException("LanguageWindow", ex);
			Shutdown();
			return;
		}

		try
		{
			MainWindow mainWindow = new MainWindow();
			((Window)(object)mainWindow).Show();
			base.MainWindow = (Window)(object)mainWindow;
			base.ShutdownMode = ShutdownMode.OnMainWindowClose;
		}
		catch (Exception ex)
		{
			DumpException("MainWindow", ex);
			Shutdown();
		}
	}

	private static void DumpException(string context, Exception ex)
	{
		string full = context + " CRASH:\n\n";
		var current = ex;
		int depth = 0;
		while (current != null && depth < 10)
		{
			full += $"[{depth}] {current.GetType().FullName}: {current.Message}\n{current.StackTrace}\n\n";
			current = current.InnerException;
			depth++;
		}

		string logPath = Path.Combine(Path.GetTempPath(), "crysome_crash.log");
		try { File.WriteAllText(logPath, full); } catch { }

		MessageBox.Show(full, "CRYSOME | t.me/CuriousCracks — " + context, MessageBoxButton.OK, MessageBoxImage.Hand);
	}

	private static void ApplyCulture(string cultureTag)
	{
		try
		{
			CultureInfo cultureInfo = ((string.IsNullOrEmpty(cultureTag) || cultureTag == "en") ? CultureInfo.InvariantCulture : new CultureInfo(cultureTag));
			Thread.CurrentThread.CurrentCulture = cultureInfo;
			Thread.CurrentThread.CurrentUICulture = cultureInfo;
			Strings.Culture = cultureInfo;
		}
		catch
		{
		}
	}

	public App()
	{
		base.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
		AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
	}

	private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
	{
		LogCrash("Dispatcher", e.Exception);
		e.Handled = true;
	}

	private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
	{
		LogCrash("Domain", e.ExceptionObject as Exception);
	}

	private void LogCrash(string source, Exception ex)
	{
		string full = $"[{DateTime.Now}] {source} CRASH:\n{ex?.ToString() ?? "Unknown error"}\n\n";
		string logPath = Path.Combine(Path.GetTempPath(), "crysome_crash.log");
		try { File.AppendAllText(logPath, full); } catch { }
		MessageBox.Show("Error: " + ex?.Message + "\n\nLog: " + logPath, "CRYSOME | t.me/CuriousCracks", MessageBoxButton.OK, MessageBoxImage.Hand);
	}

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

	[STAThread]
	[GeneratedCode("PresentationBuildTasks", "9.0.14.0")]
	public static void Main()
	{
		App app = new App();
		try
		{
			app.InitializeComponent();
		}
		catch (Exception ex)
		{
			DumpException("App.InitializeComponent (app.baml)", ex);
			return;
		}
		app.Run();
	}
}
