using Chronos.App.Shell;
namespace Chronos.App.Archiving;
///
/// The Archive views that --capture renders (archive-<view>-<theme>.png) and the screen smoke
/// tests check, on the sample archive: the tree with figures and charts, the maintenance view with its reports, the
/// rebuild dialog, the Reorganize dialog with its dry run, the Convert dialog with its dry run and New sequence chosen, and
/// the trash (Maintenance › Trash…) with deleted sequences.
///
public static class ArchiveScenes
{
public static readonly IReadOnlyList Views = ["overview", "maintenance", "rebuild", "reorganize", "convert", "trash"];
public static async Task ShowAsync(ShellViewModel shell, string view)
{
var archive = shell.Archive;
shell.Navigate(SectionKey.Archive);
archive.Dialog?.CloseCommand.Execute(null);
await archive.LoadAsync();
var db = shell.Services.Database ?? throw new InvalidOperationException("The sample index is not open.");
var locations = archive.SelectedArchive is { } selected ? await db.Sequences.ListLocationsAsync(selected.Id) : [];
// What the Reorganize view wrote leaves with it, so the sample's sizes stay the same for the views after it.
RemoveSampleFiles();
switch (view)
{
case "overview":
archive.ViewIndex = 0;
break;
case "maintenance":
archive.ViewIndex = 1;
archive.ShowReports(SampleReports.Duplicates(locations), SampleReports.Orphans(locations), locations);
break;
case "rebuild":
archive.ViewIndex = 0;
(await archive.OpenRebuildDialogAsync())?.ShowFolders(SampleReports.Folders(locations));
break;
case "reorganize":
archive.ViewIndex = 0;
// The dry run reads each sequence's sidecar, which the sample index has none of: without them every
// sequence would show "cannot be read" and Apply would stay off.
if (archive.SelectedArchive is { } reorganized) await WriteSampleSidecarsAsync(db, reorganized.RootPath, locations);
await archive.OpenReorganizeDialogAsync();
if (archive.Dialog is ReorganizeDialogViewModel reorganize)
{
reorganize.Folders.Field.Text = "{year}/{date} {title}";
await reorganize.PlanAsync();
}
break;
case "convert":
archive.ViewIndex = 0;
await archive.OpenConvertDialogAsync();
if (archive.Dialog is ConvertDialogViewModel convert && archive.SelectedArchive is { } converted)
{
convert.Show(SampleReports.Convert(converted.Id, locations));
convert.Mode = Core.Conversion.ConvertMode.NewSequence;
}
break;
case "trash":
archive.ViewIndex = 1;
await archive.OpenTrashAsync();
if (archive.Dialog is TrashDialogViewModel trash && archive.SelectedArchive is { } shown) trash.Show(SampleReports.Trash(shown.Id, locations));
break;
default:
throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown Archive view.");
}
}
///
/// A minimal sidecar for each sample sequence that has none yet: its id, title and camera, and one small stand-in photo in
/// its originals taken at its first capture, which the templates' dates and file names come from.
///
private static async Task WriteSampleSidecarsAsync(Data.ChronosDatabase db, string root, IReadOnlyList locations)
{
// A file is recorded before it is written, so one half written goes too.
var paths = new Core.Archiving.ArchivePaths(root);
byte[] photo = [0xFF, 0xD8, 0xFF, 0xD9];
var sha256 = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(photo));
foreach (var location in locations)
{
var folder = paths.Sequence(location.Folder);
if (System.IO.File.Exists(folder.ManifestPath) || await db.Sequences.GetAsync(location.Id) is not { } sequence) continue;
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(folder.ManifestPath)!);
const string file = Core.Archiving.ArchiveLayout.OriginalsFolder + "/IMG_0001.JPG";
var frames = new List();
if (sequence.FirstCapture is { } first)
{
var onDisk = System.IO.Path.Combine(folder.Folder, file);
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(onDisk)!);
SampleFiles.Add(onDisk);
System.IO.File.WriteAllBytes(onDisk, photo);
frames.Add(new Core.Archiving.SidecarFrame { Id = Guid.CreateVersion7(), File = file, Size = photo.Length, Sha256 = sha256, CapturedAt = first });
}
SampleFiles.Add(folder.ManifestPath);
Core.Archiving.ManifestStore.WriteSequence(folder.ManifestPath, new Core.Archiving.SequenceManifest
{
Id = sequence.Id,
Title = sequence.Title,
Camera = new Core.Archiving.SidecarCamera { Make = sequence.CameraMake, Model = sequence.CameraModel },
Frames = frames,
});
}
}
/// The files wrote that are still on disk.
private static readonly List SampleFiles = [];
/// Deletes the files the Reorganize view wrote for its dry run.
private static void RemoveSampleFiles()
{
foreach (var path in SampleFiles)
{
try
{
System.IO.File.Delete(path);
}
catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("capture", $"{path} of the sample stays", ex);
}
}
SampleFiles.Clear();
}
}