using System.Globalization; using System.IO; using System.Windows.Input; using Chronos.App.Infrastructure; using Chronos.Core.Archiving; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; using Chronos.Data; using Chronos.Data.Archiving; using Chronos.Data.Archiving.Jobs; using Chronos.Data.Jobs; using Chronos.Ui.Mvvm; namespace Chronos.App.Archiving; /// One entry of the trash: a deleted sequence or photos deleted from one, when it went, and Restore. public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore) { public TrashEntry Entry { get; } = entry; public string Title => Entry.Title; /// "Photos", "Sequence": what the entry holds. public string KindText => TrashEmptyPlans.KindText(Entry.Kind); /// "Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language). public string Detail => string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder)); /// "Deleted 02/10/2026 18:04". public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt)); public ICommand RestoreCommand { get; } = restore; } /// The words of an emptying of the trash (): the destructive, typed confirmation. public static class TrashEmptyPlans { /// "Photos", "Sequence", "Replaced". public static string KindText(TrashKind kind) => Loc.L("Archive.Trash.Kind." + kind); /// /// The confirmation of erasing the planned entries for good; null when the plan holds none. An entry of replaced originals /// whose conversion was deleted since says so (): erasing it may erase the last /// copy of those photos, so every such entry is named first, with why, wherever the trash lists it; the other entries /// fill the lines left () and the rest are counted. /// public static ConfirmRequest? Request(TrashEmptyPlan plan) { ArgumentNullException.ThrowIfNull(plan); if (plan.Entries.Count == 0) return null; var count = plan.Entries.Count.ToString(CultureInfo.InvariantCulture); var lastCopies = plan.Entries.Where(e => e.ConversionDeleted).ToList(); var others = plan.Entries.Where(e => !e.ConversionDeleted).ToList(); var listed = Math.Max(0, DeletePlans.ListedLines - lastCopies.Count); var lines = lastCopies.Concat(others.Take(listed)).Select(e => Loc.L("Archive.Delete.Line", e.Title, KindText(e.Kind) + Loc.Separator + Loc.Plural("Shell.Status.Photos", e.Frames) + (e.ConversionDeleted ? Loc.Separator + Loc.L("Archive.Trash.ConversionDeleted") : string.Empty), Formatting.Bytes(e.Bytes))).ToList(); if (others.Count > listed) lines.Add(Loc.Plural("Archive.Delete.More", others.Count - listed)); return new ConfirmRequest { Heading = Loc.Plural("Archive.Trash.EmptyHeading", plan.Entries.Count), Message = Loc.L("Archive.Trash.EmptyMessage", Loc.Plural("Shell.Status.Photos", plan.Photos), Loc.Plural("Archive.Delete.Files", plan.Files), Formatting.Bytes(plan.Bytes)), Detail = string.Join(Environment.NewLine, lines), IsDetailMonospaced = false, DetailToolTip = Loc.L("Tooltips.Archive.TrashEmptyPlan"), SafeText = Loc.L("Archive.Delete.Keep"), SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"), ActionText = Loc.L("Archive.Trash.Erase"), ActionToolTip = Loc.Plural("Tooltips.Archive.TrashErase", plan.Entries.Count), IsDestructive = true, TypedConfirmation = count, TypedPrompt = Loc.L("Archive.Delete.Type", count), }; } } /// /// The archive's trash (BRIEF §0.2 rule 8, §12.5): every sequence deleted from the Library or the Archive manager and the /// photos deleted from sequences (owner review 2, R6), newest first, each restorable — a sequence into its folder (or a /// free one next to it) with its ids, settings and renders, photos into their sequence after their files are re-hashed. /// Empty… erases the entries for good: a dry run, a typed confirmation, then the EmptyTrash job, which refuses when /// the trash changed since. /// public sealed class TrashDialogViewModel : ArchiveDialogViewModel { private readonly ArchiveService _archives; private readonly Core.Model.Archive _archive; private readonly Func _restored; private readonly Func? _confirm; private readonly Func? _enqueue; private readonly JobEngine? _followUps; private IReadOnlyList _rows = []; /// Asks the typed confirmation of an emptying (null: the trash cannot be emptied here). /// Queues the emptying job and says so (null: the trash cannot be emptied here). /// The engine that takes the analyses and images restored photos need again. public TrashDialogViewModel(ArchiveService archives, Core.Model.Archive archive, Func restored, Action close, Func? confirm = null, Func? enqueue = null, JobEngine? followUps = null) : base(close) { _archives = archives; _archive = archive; _restored = restored; _confirm = confirm; _enqueue = enqueue; _followUps = followUps; EmptyCommand = new AsyncRelayCommand(EmptyAsync, () => CanEmpty); } public string Heading => Loc.L("Archive.Trash.Heading", _archive.Name); public IReadOnlyList Rows { get => _rows; private set { if (!Set(ref _rows, value)) return; OnPropertyChanged(nameof(IsEmpty)); OnPropertyChanged(nameof(HasRows)); OnPropertyChanged(nameof(SummaryText)); OnPropertyChanged(nameof(EmptyToolTip)); CommandManager.InvalidateRequerySuggested(); } } public bool IsEmpty => _rows.Count == 0; /// The list shows; an empty trash is its summary sentence alone. public bool HasRows => _rows.Count > 0; /// "3 entries · 182 GB", or "The trash is empty". public string SummaryText => _rows.Count == 0 ? Loc.L("Archive.Trash.Empty") : Loc.Plural("Archive.Trash.Entries", _rows.Count) + Loc.Separator + Formatting.Bytes(_rows.Sum(r => r.Entry.Bytes)); /// Empty…: the dry run, the typed confirmation, then the job. public ICommand EmptyCommand { get; } /// Emptying is offered here, and there is something to erase. public bool CanEmpty => !IsBusy && HasRows && _confirm is not null && _enqueue is not null; public string EmptyToolTip => HasRows ? Loc.L("Tooltips.Archive.TrashEmpty") : Loc.L("Archive.Trash.Empty"); /// Reads the trash of the archive (off the UI thread). public async Task LoadAsync() { ClearError(); BusyText = Loc.L("Archive.Trash.Reading"); try { var entries = await Task.Run(() => _archives.ListTrashAsync(_archive.Id)); Rows = [.. entries.Select(Row)]; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException) { Log.Warning("archive", "Reading the trash failed", ex); ShowError(ex); } finally { BusyText = null; } } /// Shows entries read elsewhere (capture). public void Show(IReadOnlyList entries) => Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => Task.CompletedTask)))]; private TrashRowViewModel Row(TrashEntry entry) => new(entry, new AsyncRelayCommand(() => RestoreAsync(entry), () => !IsBusy)); private async Task RestoreAsync(TrashEntry entry) { ClearError(); IsBusy = true; BusyText = Loc.L("Archive.Trash.Restoring", entry.Title); try { var result = await Task.Run(() => _archives.RestoreEntryAsync(entry.ArchiveId, entry.Name, _followUps)); Log.Info("archive", $"{entry.Title} restored from the trash ({entry.Kind}, {result.Photos} photo(s), {result.Kept.Count} kept)"); BusyText = null; if (result.Kept.Count > 0) { // Photos that stay in the trash keep their entry, with what is left; the line says how many stayed and why, // and the tooltip repeats it with their names. await LoadAsync(); var (text, tip) = KeptText(result.Kept); ShowMessage(text, tip); } else { Rows = [.. _rows.Where(r => r.Entry != entry)]; } await _restored(); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException or DatabaseException or ArgumentException) { Log.Warning("archive", $"Restoring {entry.Title} failed", ex); ShowError(ex); } finally { IsBusy = false; BusyText = null; } } /// /// The line of what a restore kept in the trash, and its tooltip: one reason's sentence ("2 photos stayed in the trash: /// they could not be moved back."), or how many stayed when they stayed for different reasons. The tooltip holds that /// line, then each reason's sentence (when there are several) with its photos' names, one per line, the names counted /// past in all. /// internal static (string Text, string ToolTip) KeptText(IReadOnlyList kept) { var groups = kept.GroupBy(k => k.Reason).OrderBy(g => g.Key).ToList(); var text = groups.Count == 1 ? KeptPhoto.Sentence(groups[0].Key, groups[0].Count(), Loc.Culture) : Loc.Plural("Archive.Trash.KeptPhotos", kept.Count); var lines = new List { text }; var listed = 0; foreach (var group in groups) { if (groups.Count > 1) lines.Add(KeptPhoto.Sentence(group.Key, group.Count(), Loc.Culture)); foreach (var photo in group) { if (listed++ < DeletePlans.ListedLines) lines.Add(Formatting.LeftToRight(photo.Name)); } } if (kept.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Trash.KeptMore", kept.Count - DeletePlans.ListedLines)); return (text, string.Join(Environment.NewLine, lines)); } /// /// Empty…: measures every entry (the dry run), asks to type how many entries go, and queues the job that erases exactly /// those; the dialog closes, and the job says how it ended. /// private async Task EmptyAsync() { if (_confirm is null || _enqueue is null) return; ClearError(); IsBusy = true; BusyText = Loc.L("Archive.Trash.Checking"); TrashEmptyPlan plan; try { plan = await Task.Run(() => _archives.PlanEmptyTrashAsync(_archive.Id)); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException) { Log.Warning("archive", "The dry run of emptying the trash failed", ex); ShowError(ex); return; } finally { IsBusy = false; BusyText = null; } if (TrashEmptyPlans.Request(plan) is not { } request || !_confirm(request)) return; await _enqueue(ArchiveJobs.EmptyTrash(_archive, plan)); Close(); } }