// PRE-GENERATED (design session). DB manager popup code-behind.
using System;
using System.Windows;
using DansoriEQ.Core.Profiles;

namespace DansoriEQ.App;

public partial class DbManagerWindow : Wpf.Ui.Controls.FluentWindow
{
    private readonly IProfileDbService _service;

    public DbManagerWindow(IProfileDbService service)
    {
        InitializeComponent();
        _service = service;
        Populate(_service.GetInfo());
    }

    private void Populate(DbInfo info)
    {
        TxtTotal.Text = info.TotalProfiles.ToString("N0");
        TxtIem.Text = info.IemCount.ToString("N0");
        TxtHp.Text = info.HeadphoneCount.ToString("N0");
        TxtUpdated.Text = info.LastUpdatedUtc?.LocalDateTime.ToString("yyyy-MM-dd HH:mm") ?? "—";
        TxtSize.Text = $"{info.DbSizeBytes / 1024.0 / 1024.0:0.0} MB";
        TxtSchema.Text = $"v{info.SchemaVersion}";
        TxtPath.Text = info.DbPath;
        SourcesList.ItemsSource = info.Sources;
    }

    private async void BtnUpdate_Click(object sender, RoutedEventArgs e)
    {
        BtnUpdate.IsEnabled = false;
        UpdateProgress.IsIndeterminate = true;   // animated stripe until real fraction arrives
        UpdateProgress.Value = 0;
        LoadBars.Visibility = System.Windows.Visibility.Visible;
        LoadBars.Start();

        var progress = new Progress<DbUpdateProgress>(p =>
        {
            if (p.Fraction < 0)
            {
                // -1 = indeterminate step (extraction, unknown-length download)
                UpdateProgress.IsIndeterminate = true;
            }
            else
            {
                UpdateProgress.IsIndeterminate = false;
                UpdateProgress.Value = Math.Clamp(p.Fraction * 100, 0, 100);
            }
            TxtProgress.Text = p.Message;
        });

        try
        {
            var info = await _service.UpdateAsync(progress);
            UpdateProgress.IsIndeterminate = false;
            UpdateProgress.Value = 100;
            Populate(info);
            TxtProgress.Text = "업데이트 완료 ✓";
        }
        catch (OperationCanceledException)
        {
            TxtProgress.Text = "취소됨";
            UpdateProgress.IsIndeterminate = false;
        }
        catch (Exception ex)
        {
            TxtProgress.Text = "오류: " + ex.Message;
            UpdateProgress.IsIndeterminate = false;
        }
        finally
        {
            BtnUpdate.IsEnabled = true;
            LoadBars.Stop();
            LoadBars.Visibility = System.Windows.Visibility.Collapsed;
        }
    }

    private void BtnClose_Click(object sender, RoutedEventArgs e) => Close();
}
