using System.Windows;
using PSLauncher.Models;

namespace PSLauncher.App.Views;

public partial class UpdateAvailableDialog : Window
{
    public UpdateAvailableDialog(VersionManifest version, string releaseNotesMarkdown)
    {
        InitializeComponent();

        DataContext = new
        {
            Title = $"Proserve v{version.Version} disponible",
            Subtitle = $"Date de release : {version.ReleasedAt.ToLocalTime():dd MMMM yyyy} • {FormatSize(version.Download.SizeBytes)}",
            ReleaseNotesDocument = MarkdownTheming.BuildThemedDocument(releaseNotesMarkdown)
        };
    }

    public bool DownloadRequested { get; private set; }

    private void OnDownload(object sender, RoutedEventArgs e)
    {
        DownloadRequested = true;
        DialogResult = true;
        Close();
    }

    private void OnLater(object sender, RoutedEventArgs e)
    {
        DownloadRequested = false;
        DialogResult = false;
        Close();
    }

    private static string FormatSize(long bytes)
    {
        if (bytes <= 0) return "taille inconnue";
        string[] units = { "o", "Ko", "Mo", "Go", "To" };
        double v = bytes;
        int u = 0;
        while (v >= 1024 && u < units.Length - 1) { v /= 1024; u++; }
        return $"{v:0.#} {units[u]}";
    }
}
