using LauncherUpdater.Function;
using LauncherUpdater.HTTP;
using LauncherUpdater.Response;
using Newtonsoft.Json;
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

namespace LauncherUpdater
{
    public partial class MainWindow : Window, IComponentConnector
    {
        private readonly HttpRequest httpRequest;
        public DirectoryInfo lDir;
        private FileConfig fileConfig;

        public MainWindow()
        {
            this.httpRequest = new HttpRequest();
            this.fileConfig = new FileConfig();
            this.InitializeComponent();
            this.lDir = new DirectoryInfo(Environment.CurrentDirectory);
            this.CheckLauncherFiles();
        }

        public async Task CheckLauncherFiles()
        {
            try
            {
                foreach (Process process in Process.GetProcessesByName("LauncherIcarus"))
                    process.Kill();
                if (!Directory.Exists(Configuration.Default.LauncherDir))
                    Directory.CreateDirectory(Configuration.Default.LauncherDir);
                this.progressBar.Width = 0.0;
                double totalDownloaded = 0.0;
                ResponseListLauncherFiles get =
                    JsonConvert.DeserializeObject<ResponseListLauncherFiles>(
                        await this.httpRequest.GetLauncherFileAsync());
                if (get.TotalBytes > 0.0)
                {
                    foreach (Files k in get.File)
                    {
                        Crc32 crc32 = new Crc32();
                        string empty = string.Empty;
                        if (System.IO.File.Exists(Configuration.Default.LauncherDir + k.filename))
                        {
                            using (FileStream inputStream =
                                   System.IO.File.Open(Configuration.Default.LauncherDir + k.filename, FileMode.Open))
                            {
                                foreach (byte num in crc32.ComputeHash((Stream) inputStream))
                                    empty += num.ToString("x2").ToLower();
                            }

                            if (k.crc32 != empty)
                            {
                                int num1 = await this.DownloadArchiveAsync(k.filename,
                                    Configuration.Default.LauncherDir, k.url)
                                    ? 1
                                    : 0;
                            }
                        }
                        else
                        {
                            int num2 = await this.DownloadArchiveAsync(k.filename, Configuration.Default.LauncherDir,
                                k.url)
                                ? 1
                                : 0;
                        }

                        double num3 = k.size / get.TotalBytes * 370.0;
                        totalDownloaded += k.size;
                        this.progressBar.Width += Math.Round(num3, 0);
                    }
                }

                this.fileConfig.SetLauncherIsChecked(EncryptionHelper.Encrypt("TRUE"));
                DirectoryInfo directoryInfo = new DirectoryInfo(Environment.CurrentDirectory);
                Process.Start(new ProcessStartInfo()
                {
                    WorkingDirectory = directoryInfo.FullName + "\\Launcher\\",
                    FileName = "LauncherIcarus.exe",
                    CreateNoWindow = true
                });
                Environment.Exit(0);
                get = (ResponseListLauncherFiles) null;
            }
            catch (Exception ex)
            {
                Logger.WriteLog(Application.Current?.ToString() + " : " + ex.Message);
                Environment.Exit(0);
            }
        }

        private async Task<bool> DownloadArchiveAsync(
            string filename,
            string downloadPath,
            string url)
        {
            DownloadProgressChangedEventHandler changedEventHandler =
                (DownloadProgressChangedEventHandler) ((s, e) => { });
            DownloadDataCompletedEventHandler completedEventHandler =
                (DownloadDataCompletedEventHandler) ((s, e) => { });
            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadProgressChanged += changedEventHandler;
                webClient.DownloadDataCompleted += completedEventHandler;
                await webClient.DownloadFileTaskAsync(new Uri(Configuration.Default.ServerIP + url),
                    downloadPath + filename);
            }

            return true;
        }
    }
}