using Microsoft.UI.Xaml;
using Microsoft.Windows.Globalization;
using Sonex.Client.AppWindows;
using System;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;

namespace Sonex.Client
{
    public partial class App : Application
    {
        private LoginWindow2? _LoginWindow;
        private MainWindow? _MainWindow;

        public App()
        {
            try
            {
                var culture = new CultureInfo("en-US");

                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;
                CultureInfo.DefaultThreadCurrentCulture = culture;
                CultureInfo.DefaultThreadCurrentUICulture = culture;

                ApplicationLanguages.PrimaryLanguageOverride = "en-US";

                InitializeComponent();

                AppDomain.CurrentDomain.UnhandledException += (_, e) =>
                    File.AppendAllText("startup_crash.log", e.ExceptionObject?.ToString() + Environment.NewLine);

                TaskScheduler.UnobservedTaskException += (_, e) =>
                    File.AppendAllText("startup_crash.log", e.Exception + Environment.NewLine);

                UnhandledException += (_, e) =>
                    File.AppendAllText("startup_crash.log", e.Exception + Environment.NewLine);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            OpenLoginWindow();
        }

        public void OpenLoginWindow()
        {
            _LoginWindow = new LoginWindow2();
            _LoginWindow.PrepareBeforeShow();
            _LoginWindow.HideNative();
            _LoginWindow.Activate();
            
        }

        public void OpenMainWindow()
        {
            _MainWindow = new MainWindow();
            _MainWindow.Activate();
            Sonex.Client.Helpers.AppWindowsHelper.BringToFront(_MainWindow);

            _LoginWindow?.Close();
            _LoginWindow = null;
        }
    }
}