using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using Zerolauncher.Manager;

namespace Zerolauncher
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static bool needUpdate = false;
        static Mutex? mutex;

        static bool TryDeleteDirectory(string path, bool recursive)
        {
            try
            {
                Directory.Delete(path, recursive);
                return true;
            }
            catch (UnauthorizedAccessException)
            {
                return false;
            }
        }

        static bool CheckProcess()
        {
            Process[] processes = Process.GetProcesses();
            Process currentProcess = Process.GetCurrentProcess();
            bool processExist = false;
            foreach (Process p in processes)
            {
                if (p.ProcessName == currentProcess.ProcessName && p.Id != currentProcess.Id)
                {
                    processExist = true;
                }
            }
            return processExist;
        }

        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        protected override void OnStartup(StartupEventArgs e)
        {
            if (CheckProcess())
            {
                Trace.WriteLine("应用程序已经在运行，将其置于前台并退出");
                // 应用程序已经在运行，将其置于前台并退出
                var currentProcess = Process.GetCurrentProcess();
                foreach (var process in Process.GetProcessesByName(currentProcess.ProcessName))
                {
                    if (process.Id != currentProcess.Id)
                    {
                        SetForegroundWindow(process.MainWindowHandle);
                        break;
                    }
                }

                // 关闭当前的应用程序实例
                Shutdown();
                return;
            }
            base.OnStartup(e);

            Task.Run(async () =>
            {
                await CloundMananger.TakeQMessage();
                UpDateManager.DoCheckUpdate();
                if (UpDateManager.state)
                {
                    UpDateManager.DoUpdate();
                }
            });
            Task.Run(async () =>
            {
                if (Directory.Exists("./cache/"))
                {
                    for (int i = 0; i < 3 && !TryDeleteDirectory(@"./cache", true); i++) await Task.Delay(3000);
                }
            });
            DataStreamNew.Load();
            _ = WebApiManager.StartListener();
            AccountManager.initLoadData();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            WebApiManager.StopListener();
            if (needUpdate) Process.Start("./cache/upacket.bin");
        }
    }

}
