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

if (args.Length > 0 && args[0] == "--version")
{
    Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Version);
    return;
}

if (args.Length > 0) return;

var logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.File("update.log", LogEventLevel.Debug)// restricted... is Optional
    .CreateLogger();
try
{
    string fileName = "VeloeMinecraftLauncher";
    using var httpClient = new HttpClient();

    if (OperatingSystem.IsWindows())
        fileName += ".exe";

    if (OperatingSystem.IsWindows() && File.Exists(fileName))
    {
        FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(fileName);
        LatestLauncherVersion? latestLauncherVersion;

        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 (latestLauncherVersion?.Latest is not null && fileVersionInfo?.FileVersion is not null)
        {
            logger.Information("Latest launcher version on server: {0}", latestLauncherVersion.Latest);
            logger.Information("Launcher version: {0}", fileVersionInfo.FileVersion);

            if (fileVersionInfo?.FileVersion is not null && !(new Version(latestLauncherVersion.Latest) > new Version(fileVersionInfo.FileVersion)))
            {
                logger.Information("No update required.");
                return;
            }
        }
    }
    
    if(OperatingSystem.IsLinux())
    {
        logger.Warning("Force update mode only.");
    }

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

        url = OperatingSystem.IsWindows() ? 
                OperatingSystem.IsWindowsVersionAtLeast(10, 0, 14393) ? 
                    "https://files.veloe.link/launcher/update/latest.zip" : 
                    "https://files.veloe.link/launcher/update/latest_net7.0.zip" : 
                OperatingSystem.IsLinux() ?
                    "https://files.veloe.link/launcher/update/latest_linux-x64.zip" :
                    string.Empty;

        if (url == String.Empty) return;

        using HttpResponseMessage response = await httpClient.GetAsync(new System.Uri(url), HttpCompletionOption.ResponseHeadersRead);
        response.EnsureSuccessStatusCode();
        using Stream contentStream = await response.Content.ReadAsStreamAsync();
        using FileStream fileStream = File.OpenWrite("latest.zip");
        await contentStream.CopyToAsync(fileStream);
    }
    catch (Exception)
    {
        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());
    if (ex.StackTrace is not null)
        logger.Error(ex.StackTrace);
}


