// See https://aka.ms/new-console-template for more information
using Serilog;
using Serilog.Events;
using System.Diagnostics;
using System.IO.Compression;
using System.Net;
using System.Text.Json;
using VeloeLauncherUpdater;

var logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.File("update.log", LogEventLevel.Debug)// restricted... is Optional
    .CreateLogger();

try
{
    string fileName = "VeloeMinecraftLauncher";
    if (OperatingSystem.IsWindows())
        fileName += ".exe";
    if (File.Exists(fileName))
    {
        FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(fileName);
        LatestLauncherVersion latestLauncherVersion;

        using (var httpClient = new HttpClient())
        {
            var jsonData = string.Empty;
            try
            {
                jsonData = httpClient.GetStringAsync("https://files.veloe.link/launcher/update/versions.json").Result;
            }
            catch (Exception)
            {
                logger.Error("Error occured on getting versions.json from the server.");
                throw;
            }

            latestLauncherVersion = string.IsNullOrEmpty(jsonData)
                        ? new LatestLauncherVersion()
                        : JsonSerializer.Deserialize<LatestLauncherVersion>(jsonData, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
        }

        if (OperatingSystem.IsLinux())
        {
            logger.Information("Manual updates only.");
            return;
        }

        if (latestLauncherVersion != null)
        {
            logger.Information("Latest launcher version on server: {0}", latestLauncherVersion.Latest);
            logger.Information("Launcher version: {0}", fileVersionInfo.FileVersion);

            if (!(new Version(latestLauncherVersion.Latest) > new Version(fileVersionInfo.FileVersion)))
            {
                logger.Information("No update required.");
                return;
            }
        }
    }

    WebClient webClient = new WebClient();
    try
    {
        logger.Information("Downloading latest.zip");
        string url = String.Empty;

        if (OperatingSystem.IsWindows())
            url = "https://files.veloe.link/launcher/update/latest.zip";

        if (OperatingSystem.IsLinux())
            url = "https://files.veloe.link/launcher/update/latest_linux-x64.zip";

        if (url == String.Empty)
            return;

        webClient.DownloadFile(new System.Uri(url), "latest.zip"); ;
    }
    catch (Exception ex)
    {
        logger.Error("Error occured on getting latest.zip from the server.");
        throw;
    }

    logger.Information("Unpacking latest.zip");
    ZipFile.ExtractToDirectory($"latest.zip", Directory.GetCurrentDirectory(), true);

    logger.Information("Deleting latest.zip");
    File.Delete($"latest.zip");
}
catch (Exception ex)
{
    logger.Error(ex.Message);
    logger.Error("Path exe: {0}", Directory.GetCurrentDirectory());
    logger.Error(ex.StackTrace);
}


