using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
///
/// "Delete…" of the Library and the Archive manager (BRIEF §0.2 rule 8, §12.2, §12.5) in an in-window dialog that says
/// how far it is and stops on Cancel: the archive engine's dry run, sequence by sequence; the destructive confirmation
/// that asks to type the number of sequences (DESIGN §4); then the move into the archives' trash, each sequence whole
/// or not at all. The toast that follows names what moved and brings it back.
///
public sealed class DeleteDialogViewModel : ArchiveDialogViewModel
{
private readonly ShellViewModel _shell;
private readonly IReadOnlyList _ids;
private CancellationTokenSource? _run;
private double _progress;
public DeleteDialogViewModel(ShellViewModel shell, IReadOnlyList sequenceIds, Action close)
: base(close)
{
_shell = shell;
_ids = sequenceIds;
}
/// "Deleting 3 sequences".
public string Heading => Loc.Plural("Archive.Delete.Progress", _ids.Count);
/// 0–1 of the dry run, then of the move.
public double Progress { get => _progress; private set => Set(ref _progress, value); }
protected override bool CanStop => _run is not null;
/// Stops the dry run, or the move after the sequence that is moving.
protected override void Stop() => _run?.Cancel();
public override void Dispose()
{
_run?.Cancel();
base.Dispose();
}
/// Plans, asks, deletes and offers to undo, then closes; true when something moved to the trash.
public async Task RunAsync()
{
using var run = _run = new CancellationTokenSource();
IsBusy = true;
try
{
if (_shell.Services.Archives is not { } archives || _ids.Count == 0) return false;
if (await PlanAsync(archives, run.Token) is not { } plan) return false;
if (DeletePlans.Request(plan) is not { } request)
{
_shell.Notify(Loc.L("Archive.Delete.Nothing"), string.Join(Environment.NewLine, DeletePlans.Blocked(plan, DeletePlans.BlockedLines)));
return false;
}
BusyText = null;
if (!_shell.Services.Dialogs.Confirm(request) || !await SequenceDeletion.CloseEditorAsync(_shell, plan)) return false;
return await DeleteAsync(archives, plan, run.Token);
}
finally
{
_run = null;
IsBusy = false;
Close();
}
}
/// The dry run; null when it was stopped or failed (said in a toast).
private async Task PlanAsync(ArchiveService archives, CancellationToken cancellationToken)
{
var checking = new Progress(n => Report("Archive.Delete.Checking", n, _ids.Count));
try
{
return await Task.Run(() => archives.PlanDeleteAsync(_ids, checking, cancellationToken), cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{
Log.Warning("archive", "Delete dry run failed", ex);
_shell.Notify(Loc.L("Archive.Delete.Failed"), ArchiveFailures.Cause(ex));
return null;
}
}
///
/// Moves the planned sequences; whatever moved before a stop or a failure is read back from the trash, so the toast
/// names it and offers to bring it back.
///
private async Task DeleteAsync(ArchiveService archives, DeletePlan plan, CancellationToken cancellationToken)
{
var started = DateTimeOffset.UtcNow;
var moving = new Progress(n => Report("Archive.Delete.Moving", n, plan.Steps.Count));
Report("Archive.Delete.Moving", 0, plan.Steps.Count);
Exception? failure = null;
try
{
await Task.Run(() => archives.DeleteAsync(plan, Environment.UserName, moving, cancellationToken), cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
Log.Info("archive", "Delete stopped between two sequences");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or StaleDeletePlanException or NewerFormatException
or ArgumentException or DatabaseException)
{
Log.Warning("archive", "Delete failed", ex);
failure = ex;
}
var moved = await MovedAsync(archives, plan, started);
var removed = await RemovedRowsAsync(plan);
Log.Info("archive", $"{moved.Count} sequence(s) moved to the trash, {removed} without a folder removed from the index");
await SequenceDeletion.RefreshAsync(_shell);
var undo = moved.Count == 0 ? null : new AsyncRelayCommand(() => SequenceDeletion.RestoreAsync(_shell, moved));
if (failure is not null)
_shell.Notify(Loc.L("Archive.Delete.Failed"), ArchiveFailures.Cause(failure), undo is null ? null : Loc.L("Archive.Delete.Undo"), Loc.L("Tooltips.Archive.DeleteUndo"),
undo is null ? null : () => undo.Execute(null));
else if (moved.Count > 0)
_shell.Notify(Loc.Plural("Archive.Delete.Done", moved.Count), Loc.L("Archive.Delete.Kept"), Loc.L("Archive.Delete.Undo"),
Loc.L("Tooltips.Archive.DeleteUndo"), () => undo!.Execute(null));
else if (removed > 0)
_shell.Notify(Loc.Plural("Archive.Delete.Removed", removed));
return moved.Count + removed > 0;
}
/// The trash entries this run made: the planned sequences that entered their archive's trash since it started.
private static async Task> MovedAsync(ArchiveService archives, DeletePlan plan, DateTimeOffset started)
{
var planned = plan.Steps.Where(s => s.TrashFolder is not null).Select(s => s.Sequence.Id).ToHashSet();
var moved = new List();
foreach (var archive in plan.Steps.Where(s => s.TrashFolder is not null).Select(s => s.Sequence.ArchiveId).Distinct())
{
try
{
var entries = await Task.Run(() => archives.ListTrashAsync(archive));
moved.AddRange(entries.Where(e => planned.Contains(e.SequenceId) && e.DeletedAt >= started));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{
Log.Warning("archive", "The trash could not be read after a delete", ex);
}
}
return moved;
}
/// Planned sequences without a folder (nothing to keep in a trash) whose rows are gone.
private async Task RemovedRowsAsync(DeletePlan plan)
{
if (_shell.Services.Database is not { } db) return 0;
var removed = 0;
foreach (var step in plan.Steps.Where(s => s.TrashFolder is null))
{
if (await db.Sequences.GetAsync(step.Sequence.Id) is null) removed++;
}
return removed;
}
private void Report(string key, int done, int total)
{
BusyText = Loc.L(key, Formatting.Count(done), Formatting.Count(total));
Progress = total == 0 ? 0 : (double)done / total;
}
}