using System.Diagnostics;
using System.IO;
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 bool TryDeleteDirectory(string path, bool recursive)
        {
            try
            {
                Directory.Delete(path, recursive);
                return true;
            }
            catch (UnauthorizedAccessException)
            {
                return false;
            }
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            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);
                }
            });
            DataStream.Load();
            _ = WebApiManager.StartListener();
            AccountManager.initLoadData();
        }

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

}
