using LauncherUpdater.Function;
using LauncherUpdater.HTTP;
using LauncherUpdater.Response;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Hashing;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;

namespace LauncherUpdater
{
    public partial class MainWindow : Window, IComponentConnector
    {
        private readonly HttpRequest _httpRequest;
        private readonly FileConfig _fileConfig;

        public MainWindow()
        {
            _httpRequest = new HttpRequest();
            _fileConfig = new FileConfig();
            InitializeComponent();
            CheckLauncherFiles();
        }

        private async Task CheckLauncherFiles()
        {
            try
            {
                foreach (var process in Process.GetProcessesByName("LauncherIcarus"))
                {
                    process.Kill();
                }

                if (!Directory.Exists(Configuration.Default.LauncherDir))
                {
                    Directory.CreateDirectory(Configuration.Default.LauncherDir);
                }

                ProgressBar.Width = 0.0;
                var launcherFiles = JsonConvert.DeserializeObject<ResponseListLauncherFiles>(
                    await _httpRequest.GetLauncherFileAsync()
                );
                if (launcherFiles?.TotalBytes > 0.0)
                {
                    foreach (var file in launcherFiles.Files)
                    {
                        var hash = string.Empty;
                        if (File.Exists(Configuration.Default.LauncherDir + file.Filename))
                        {
                            using (var fileStream =
                                   File.Open(Configuration.Default.LauncherDir + file.Filename, FileMode.Open)
                                  )
                            {
                                using (var memoryStream = new MemoryStream())
                                {
                                    await fileStream.CopyToAsync(memoryStream);
                                    hash = Crc32.Hash(memoryStream.ToArray())
                                        .Aggregate(hash, (current, next) => current + next.ToString("x2"))
                                        .ToLower();
                                }
                            }
                        }

                        if (file.Crc32 != hash)
                        {
                            await DownloadArchiveAsync(file.Filename, Configuration.Default.LauncherDir, file.Url);
                        }

                        var num3 = file.Size / launcherFiles.TotalBytes * 370.0;
                        ProgressBar.Width += Math.Round(num3, 0);
                    }
                }

                _fileConfig.SetLauncherIsChecked(EncryptionHelper.Encrypt("TRUE"));
                Process.Start(new ProcessStartInfo
                {
                    WorkingDirectory = Configuration.Default.LauncherDir,
                    FileName = "LauncherIcarus.exe",
                    CreateNoWindow = true,
                });
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Logger.WriteLog(Application.Current + " : " + ex.Message);
                Environment.Exit(0);
            }
        }

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