using Chronos.App.Infrastructure; using Chronos.App.Settings; using Chronos.Core.Archiving; using Chronos.Core.Import; using Chronos.Core.Localization; using Chronos.Core.Naming; namespace Chronos.App.Import; /// Figures of a plan for the Plan panel header and the Import button (Import.html). public sealed record PlanTotals(int Sessions, int Photos, int CopyCount, long CopyBytes, int Duplicates, int ImportedBefore, int Problems, long? FreeAfter, TimeSpan Estimate) { public bool HasEnoughSpace => FreeAfter is not < 0; /// "3 sessions · 4,812 photos · 96.2 GB · about 12 min". public string Text => SummaryText + Loc.Separator + Loc.L("Import.Plan.About", Formatting.Duration(Estimate)); /// "3 sessions · 4,812 photos · 96.2 GB": the plan without its time estimate. public string SummaryText => string.Join(Loc.Separator, Loc.Plural("Import.Plan.Sessions", Sessions), Loc.Plural("Shell.Status.Photos", Photos), Formatting.Bytes(CopyBytes)); /// "0 duplicates" (already in the archive by hash). public string DuplicatesText => Loc.Plural("Import.Plan.Duplicates", Duplicates); /// "12 imported before" (same file from this card), or empty. public string ImportedBeforeText => ImportedBefore > 0 ? Loc.Plural("Import.Plan.ImportedBefore", ImportedBefore) : string.Empty; /// "2.1 TB free after import", "3.2 GB missing", or empty when the volume does not report its space. public string SpaceText => FreeAfter switch { null => string.Empty, < 0 => Loc.L("Import.Plan.SpaceMissing", Formatting.Bytes(-FreeAfter.Value)), _ => Loc.L("Import.Plan.FreeAfter", Formatting.Bytes(FreeAfter.Value)), }; /// "Import 4,812 photos". public string ImportText => Loc.Plural("Import.Start", CopyCount); } /// One row of the session table: what the planner grouped and where it goes. /// The title the user typed; null when none. /// Title the sequence gets when the user types none (a whole folder's name, else its folder name). /// The session starts a new sequence (false: it continues one imported before). /// Card path of the session's first photo (where a merge joins it to the previous session). /// /// Number of the earlier session it can merge into (same camera and format; for a whole folder, same format whatever the /// camera); null for none. /// public sealed record PlanSessionRow(int Number, string SessionKey, string? Title, string DefaultTitle, string TimeText, string FramesText, string SizeText, string CameraText, string TargetText, bool IsNew, string FirstPath, int? MergesInto); public enum PlanRowKind { Session, File, } /// A line of "Show plan": a session heading and its folder, or one file (card path) and its destination path. /// A file that is not the first of its session: a new session can start there. public sealed record PlanDetailRow(PlanRowKind Kind, string Source, string Destination, string ActionText, string SizeText, bool IsSkipped, bool CanSplit) { /// A file's name on the card (its session heading shows the rest); the heading itself for a session. public string SourceText => Kind == PlanRowKind.File ? NameOf(Source) : Source; /// The file's new name (its session shows the folder); the folder for a session. public string DestinationText => Kind == PlanRowKind.File ? NameOf(Destination) : Destination; /// "Split at IMG_0042.JPG": the row's split button as screen readers announce it. public string SplitName => Loc.L("Import.Details.SplitName", SourceText); private static string NameOf(string path) => path[(path.LastIndexOf('/') + 1)..]; } /// Everything "Show plan" lists: every file to its destination, the totals and the conflicts. public sealed record PlanDetails(IReadOnlyList Rows, string TotalsText, IReadOnlyList Conflicts); /// /// Turns an into what the Import screen shows (BRIEF §12.4 "Plan before touching disk") and /// applies the choices that need no new scan of the card: the duplicate choice and session titles. /// public static class ImportPlans { /// Planning speed assumption for the estimate: a UHS-I card read plus the read-back of the copy. public const double BytesPerSecond = 80e6; public const double VerifiedBytesPerSecond = 55e6; public static TimeSpan Estimate(long bytes, bool verify) => TimeSpan.FromSeconds(System.Math.Ceiling(bytes / (verify ? VerifiedBytesPerSecond : BytesPerSecond))); public static PlanTotals Totals(ImportPlan plan, bool verify) => new( plan.Sessions.Count, plan.FileCount, plan.CopyCount, plan.CopyBytes, plan.Items.Count(i => i.ExistingFrameId is not null), plan.Items.Count(i => i.Action == ImportAction.SkipImported), plan.Problems.Count, plan.AvailableBytes is { } free ? free - plan.CopyBytes : null, Estimate(plan.CopyBytes, verify)); /// /// The plan with every photo already in the archive skipped or imported again, as the planner would have decided /// (BRIEF §13: skip, or import again; never overwrite). /// public static ImportPlan WithDuplicates(ImportPlan plan, DuplicatePolicy policy) => plan with { Sessions = [ .. plan.Sessions.Select(s => s with { Items = [ .. s.Items.Select(i => i.ExistingFrameId is null || i.Action == ImportAction.SkipImported ? i : i with { Action = policy == DuplicatePolicy.Skip ? ImportAction.SkipInArchive : ImportAction.Copy }), ], }), ], }; /// /// The plan with the typed session titles (when no template uses {title}, so no name changes); a session /// without one keeps its default title (a whole folder's name). /// public static ImportPlan WithTitles(ImportPlan plan, IReadOnlyDictionary titles) => plan with { Sessions = [ .. plan.Sessions.Select(s => s with { Title = titles.TryGetValue(s.SessionKey, out var t) && !string.IsNullOrWhiteSpace(t) ? t.Trim() : s.DefaultTitle, }), ], }; /// Folders of sequences already in the archive (a session there continues it). public static IReadOnlyList Sessions(ImportPlan plan, ImportDestinationKind destination, IReadOnlySet existingFolders) => [ .. plan.Sessions.Select(s => { var isNew = !existingFolders.Contains(s.Folder); var leaf = s.Folder[(s.Folder.LastIndexOf('/') + 1)..]; var target = destination switch { ImportDestinationKind.Server => Loc.L("Import.Session.Server"), ImportDestinationKind.Folder => s.Folder, _ => Loc.L(isNew ? "Import.Session.New" : "Import.Session.Adds", s.Folder), }; // The field shows a typed title only; the default (a whole folder's name, else the folder's) is its placeholder. var typed = s.Title is { } title && title != s.DefaultTitle ? title : null; return new PlanSessionRow(s.Number, s.SessionKey, typed, s.DefaultTitle ?? leaf, TimeText(s), FramesText(s), Formatting.Bytes(s.Items.Sum(i => i.Size)), CameraText(plan, s), target, isNew, s.Items.Count > 0 ? s.Items[0].SourcePath : string.Empty, MergeTarget(plan, s)?.Number); }), ]; /// /// "Canon EOS R5"; for a whole folder, one row per format, the format too and how many bodies took the photos: /// "Canon EOS R5 · CR3", "2 cameras · JPEG". /// private static string CameraText(ImportPlan plan, PlannedSession s) { var camera = PathTemplate.CameraName(s.CameraMake, s.CameraModel); if (plan.Grouping != ImportGrouping.WholeFolder) return camera; var bodies = s.Cameras > 1 ? Loc.Plural("Import.Session.Cameras", s.Cameras) : camera; return string.Join(Loc.Separator, new[] { bodies, FormatNames.Of(s.Format) }.Where(t => t.Length > 0)); } /// /// The session joins when the user merges it (BRIEF §13): the one before it of the same /// camera body and format, whose last photo precedes its first; sessions of other cameras or formats never merge. /// A whole folder's parts (split by the user) join the part before them of the same format, whatever the camera. /// public static PlannedSession? MergeTarget(ImportPlan plan, PlannedSession session) => plan.Sessions.TakeWhile(s => !ReferenceEquals(s, session)) .LastOrDefault(s => s.Format == session.Format && (plan.Grouping == ImportGrouping.WholeFolder || (s.CameraMake == session.CameraMake && s.CameraModel == session.CameraModel && s.CameraSerial == session.CameraSerial))); /// "Show plan": every file and where it goes, with the conflicts the plan resolved or reports. public static PlanDetails Details(ImportPlan plan, ImportDestinationKind destination, bool verify) { var rows = new List(plan.FileCount + plan.Sessions.Count); foreach (var s in plan.Sessions) { var folder = DestinationFolder(s, destination); rows.Add(new PlanDetailRow(PlanRowKind.Session, Loc.L("Import.Details.Session", s.Number, TimeText(s)), folder, Loc.Plural("Shell.Status.Photos", s.Items.Count), Formatting.Bytes(s.Items.Sum(i => i.Size)), false, false)); for (var i = 0; i < s.Items.Count; i++) { var item = s.Items[i]; rows.Add(new PlanDetailRow(PlanRowKind.File, item.SourcePath, folder + "/" + item.FileName, ActionText(item), Formatting.Bytes(item.Size), item.Action != ImportAction.Copy, i > 0)); } } var totals = Totals(plan, verify); var conflicts = new List(); foreach (var problem in plan.Problems) conflicts.Add(Loc.L("Import.Details.Unreadable", BidiText.Ltr(problem.RelativePath), problem.Message)); if (totals.Duplicates > 0) conflicts.Add(totals.DuplicatesText); if (!totals.HasEnoughSpace) conflicts.Add(totals.SpaceText); var text = string.Join(Loc.Separator, new[] { Loc.Plural("Import.Details.Files", plan.FileCount), Loc.L("Import.Details.Copy", Formatting.Count(plan.CopyCount), Formatting.Bytes(plan.CopyBytes)), totals.ImportedBeforeText, totals.Duplicates > 0 ? totals.DuplicatesText : string.Empty, }.Where(t => t.Length > 0)); return new PlanDetails(rows, text, conflicts); } /// The destination of a session as the user will find it: the archive's originals folder, the folder, or the server. public static string DestinationFolder(PlannedSession session, ImportDestinationKind destination) => destination switch { ImportDestinationKind.Archive => session.Folder + "/" + ArchiveLayout.OriginalsFolder, ImportDestinationKind.Server => Loc.L("Import.Session.Server"), _ => session.Folder, }; /// The first files the plan copies, as folder/name (the name alone for the server). public static IReadOnlyList FirstDestinations(ImportPlan plan, ImportDestinationKind destination, int count = 3) => [ .. plan.Sessions.SelectMany(s => s.Items.Where(i => i.Action == ImportAction.Copy) .Select(i => destination == ImportDestinationKind.Server ? i.FileName : s.Folder + "/" + i.FileName)) .Take(count), ]; /// /// "→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2 · 2026-09-28_18-02-13_0002.CR2 · …" (BRIEF §7.1: the first /// three names): a name in the same folder as the one before it is shown without the folder. Empty without names. /// public static string NamePreview(IReadOnlyList paths) { if (paths.Count == 0) return string.Empty; var shown = new List(paths.Count); for (var i = 0; i < paths.Count; i++) { var folder = FolderOf(paths[i]); shown.Add(i > 0 && folder == FolderOf(paths[i - 1]) ? paths[i][(folder.Length == 0 ? 0 : folder.Length + 1)..] : paths[i]); } return Loc.L("Import.Names.Preview", string.Join(Loc.Separator, shown)); } private static string FolderOf(string path) => path.LastIndexOf('/') is var slash and >= 0 ? path[..slash] : string.Empty; private static string ActionText(PlannedItem item) => item.Action switch { ImportAction.SkipImported => Loc.L("Import.Action.ImportedBefore"), ImportAction.SkipInArchive => Loc.L("Import.Action.Duplicate"), _ when item.ExistingFrameId is not null => Loc.L("Import.Action.Again"), _ => Loc.L("Import.Action.Copy"), }; /// /// "28/09/2026 · 18:02 → 20:04"; one that ends on another day (a whole folder, often) shows both dates: /// "28/09/2026 18:02 → 06/10/2026 18:00". Bidi never mirrors an arrow, so a right-to-left language reads it from its /// own resource with the arrow pointing from the start to the end in its reading order. /// private static string TimeText(PlannedSession s) => s.End.Date == s.Start.Date ? Loc.L(Loc.IsRightToLeft ? "Import.Session.TimeRtl" : "Import.Session.Time", Formatting.Date(s.Start), s.Start.ToString("t", Loc.Culture), s.End.ToString("t", Loc.Culture)) : Loc.L(Loc.IsRightToLeft ? "Import.Session.TimeDaysRtl" : "Import.Session.TimeDays", Formatting.Date(s.Start), s.Start.ToString("t", Loc.Culture), Formatting.Date(s.End), s.End.ToString("t", Loc.Culture)); /// "3,600 · 2 s": photos and the median interval between them. private static string FramesText(PlannedSession s) { var interval = MedianInterval(s.Items); var count = Formatting.Count(s.Items.Count); return interval is { } median ? Loc.L("Import.Session.Frames", count, Formatting.Duration(median)) : count; } internal static TimeSpan? MedianInterval(IReadOnlyList items) { if (items.Count < 2) return null; var gaps = new List(items.Count - 1); for (var i = 1; i < items.Count; i++) gaps.Add((items[i].CapturedAt - items[i - 1].CapturedAt).TotalSeconds); gaps.Sort(); var middle = gaps.Count / 2; var seconds = gaps.Count % 2 == 1 ? gaps[middle] : (gaps[middle - 1] + gaps[middle]) / 2; return TimeSpan.FromSeconds(System.Math.Max(0, seconds)); } }