using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using ClawdDotNet.Desktop.ViewModels;

namespace ClawdDotNet.Desktop.Views;

public partial class BackupPageView : UserControl
{
    public BackupPageView()
    {
        InitializeComponent();
    }

    protected override void OnDataContextChanged(EventArgs e)
    {
        base.OnDataContextChanged(e);
        if (DataContext is BackupPageViewModel vm)
        {
            vm.RequestRestoreDialog += OnRequestRestoreDialog;
        }
    }

    private async Task<RestoreResultData?> OnRequestRestoreDialog(RestoreBackupViewModel vm)
    {
        var topLevel = TopLevel.GetTopLevel(this);
        if (topLevel is Window window)
        {
            var dialog = new RestoreBackupWindow { DataContext = vm };
            await dialog.ShowDialog(window);
            return vm.Result;
        }
        return null;
    }

    private async void OnBrowseTargetFolder(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not BackupPageViewModel vm) return;

        var topLevel = TopLevel.GetTopLevel(this);
        if (topLevel?.StorageProvider is null) return;

        var folders = await topLevel.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
        {
            Title = "Zielordner für Sicherungen wählen",
            AllowMultiple = false
        });

        if (folders.Count > 0 && folders[0].TryGetLocalPath() is { } path)
        {
            vm.TargetFolder = path;
            vm.SaveSettings();
            vm.RefreshBackupListCommand.Execute(null);
        }
    }
}
