PhotoRenamer/PhotoRenamerGui/MainWindowViewModel.cs
2023-11-04 12:08:53 +01:00

78 lines
2.5 KiB
C#

using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Platform.Storage;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PhotoRenamer;
namespace PhotoRenamerGui;
public partial class MainWindowViewModel : ObservableObject
{
[ObservableProperty] private string? _inputFolder;
[ObservableProperty] private string? _outputFolder;
public ObservableCollection<MediaFile> MediaFiles { get; } = new();
[RelayCommand]
private async Task SelectInputFolderAsync()
{
InputFolder = await SearchFolderAsync();
}
[RelayCommand]
private async Task SelectOutputFolderAsync()
{
OutputFolder = await SearchFolderAsync();
}
private static async Task<string?> SearchFolderAsync()
{
var storageProvider = (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)
?.MainWindow?
.StorageProvider;
if (storageProvider is null) return "<not accessible>";
var result = await storageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions());
return result.Count > 0 ? result[0].TryGetLocalPath() : null;
}
partial void OnInputFolderChanged(string? value)
{
UpdatePreviewList();
}
partial void OnOutputFolderChanged(string? value)
{
UpdatePreviewList();
}
private void UpdatePreviewList()
{
MediaFiles.Clear();
if (string.IsNullOrWhiteSpace(InputFolder)) return;
if (string.IsNullOrWhiteSpace(OutputFolder)) return;
var allFiles = FolderExtension.GetAllFiles(InputFolder);
foreach (var file in allFiles)
{
var source = Path.GetRelativePath(InputFolder, file);
var date = MediaFileExtension.GetDateTimeFromSourceFile(file);
var target = FolderExtension.BuildTargetDirectoryByDate(OutputFolder, DateOnly.FromDateTime(date));
MediaFiles.Add(new MediaFile(true, source, Path.GetRelativePath(OutputFolder, target)));
}
//TODO
}
}
public class MediaFile(bool isSelected, string? sourceDirectory, string? targetDirectory) : ObservableObject
{
public bool IsSelected { get=> isSelected;
set => SetProperty(ref isSelected, value);
}
public string? SourceDirectory { get; } = sourceDirectory;
public string? TargetDirectory { get; } = targetDirectory;
}