using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
namespace Artemis.UI.Shared.Services.Builders;
///
/// Represents a builder that can create a .
///
public class OpenFileDialogBuilder
{
private readonly Window _parent;
private readonly FilePickerOpenOptions _options;
private List? _fileTypeFilters;
///
/// Creates a new instance of the class.
///
/// The parent window that will host the dialog.
internal OpenFileDialogBuilder(Window parent)
{
_parent = parent;
_options = new FilePickerOpenOptions();
}
///
/// Indicate that the user can select multiple files.
///
public OpenFileDialogBuilder WithAllowMultiple()
{
_options.AllowMultiple = true;
return this;
}
///
/// Set the title of the dialog
///
public OpenFileDialogBuilder WithTitle(string? title)
{
_options.Title = title;
return this;
}
///
/// Set the initial directory of the dialog
///
public OpenFileDialogBuilder WithDirectory(string? directory)
{
_options.SuggestedStartLocation = directory != null ? _parent.StorageProvider.TryGetFolderFromPathAsync(directory).GetAwaiter().GetResult() : null;
return this;
}
///
/// Add a filter to the dialog
///
public OpenFileDialogBuilder HavingFilter(Action configure)
{
FileDialogFilterBuilder builder = new();
configure(builder);
_fileTypeFilters ??= new List();
_fileTypeFilters.Add(builder.Build());
_options.FileTypeFilter = _fileTypeFilters;
return this;
}
///
/// Asynchronously shows the file dialog.
///
///
/// A task that on completion returns an array containing the full path to the selected
/// files, or null if the dialog was canceled.
///
public async Task ShowAsync()
{
IReadOnlyList files = await _parent.StorageProvider.OpenFilePickerAsync(_options);
return files.Count == 0 ? null : files.Select(f => f.Path.LocalPath).ToArray();
}
}