using System.IO;
using Chronos.Data;
namespace Chronos.App.Archiving;
/// The archive the Import and Archive screens work on: the one at the remembered root, else the first indexed.
public static class CurrentArchive
{
public static Core.Model.Archive? Pick(IReadOnlyList archives, string? lastRoot)
{
if (archives.Count == 0) return null;
if (string.IsNullOrWhiteSpace(lastRoot)) return archives[0];
return At(archives, lastRoot) ?? archives[0];
}
/// The archive indexed at ; null when none is (Settings › Archive never edits another one).
public static Core.Model.Archive? At(IReadOnlyList archives, string root)
{
var wanted = Normalize(root);
return archives.FirstOrDefault(a => string.Equals(Normalize(a.RootPath), wanted, StringComparison.OrdinalIgnoreCase));
}
public static async Task FindAsync(ChronosDatabase db, string? lastRoot, CancellationToken cancellationToken = default) =>
Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), lastRoot);
private static string Normalize(string path)
{
try
{
return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return path;
}
}
}