2019-11-16 01:00:17 +00:00
|
|
|
|
using System;
|
2019-11-16 01:47:07 +00:00
|
|
|
|
using System.Linq;
|
2019-11-17 01:22:13 +00:00
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
2019-11-16 01:00:17 +00:00
|
|
|
|
using Avalonia;
|
|
|
|
|
|
|
|
|
|
using BFR.DataModels;
|
|
|
|
|
|
|
|
|
|
namespace BFR.Operations
|
|
|
|
|
{
|
|
|
|
|
public abstract class Operation : AvaloniaObject
|
|
|
|
|
{
|
2019-11-16 01:47:07 +00:00
|
|
|
|
// Needs to be avalonia property to update UI with any potential error.
|
2019-11-17 03:47:17 +00:00
|
|
|
|
private readonly AvaloniaProperty<string> errorProperty = AvaloniaProperty.Register<MainWindow, string>(nameof(Error), defaultValue: "");
|
2019-11-16 01:00:17 +00:00
|
|
|
|
public string Error { get => GetValue(errorProperty); set => SetValue(errorProperty, value); }
|
|
|
|
|
public bool IsEnabled { get; set; } = true;
|
|
|
|
|
public abstract string Name { get; }
|
|
|
|
|
public abstract string Description { get; }
|
|
|
|
|
|
2019-11-16 01:47:07 +00:00
|
|
|
|
protected abstract void ApplyToInternal(IList<FileModel> files);
|
2019-11-16 01:00:17 +00:00
|
|
|
|
|
2019-11-16 01:47:07 +00:00
|
|
|
|
public void ApplyTo(IList<FileModel> files)
|
2019-11-16 01:00:17 +00:00
|
|
|
|
{
|
2019-11-16 01:47:07 +00:00
|
|
|
|
// Backup of all changes thus far, in case something goes wrong
|
|
|
|
|
var backup = files.Select(file => file.Path).ToList();
|
|
|
|
|
try
|
|
|
|
|
{
|
2019-11-17 01:22:13 +00:00
|
|
|
|
if(IsEnabled)
|
|
|
|
|
ApplyToInternal(files); // Try to apply operation
|
|
|
|
|
Error = ""; // If successul, remove any previous error
|
2019-11-16 01:47:07 +00:00
|
|
|
|
}
|
|
|
|
|
catch (OperationException e) { Error = e.Message; } // If expected, show user a concise and descriptive message
|
|
|
|
|
catch (Exception e) { Error = $"Unexpected {e}"; } // If not, hint with the exception thrown that this is unexpected behaviour
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
if (Error != "") // If something went wrong, restore backup
|
|
|
|
|
for (int i = 0; i < files.Count; i++)
|
|
|
|
|
files[i].Path = backup[i];
|
|
|
|
|
}
|
2019-11-16 01:00:17 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|