using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Chronos.Core.Project;
///
/// The portable form of a project (owner review 2, R8): the settings with every frame position (exclusions, hero, camera
/// keyframes) parked by photo as , so the same text means the same thing on
/// every copy of the sequence (the archive, a workspace's proxies, a server) whatever frames were inserted or removed
/// since. Project versions store this form; a copy places the positions on its own frames when it opens one
/// (). The text is canonical (), so equal settings give equal text and an
/// equal .
///
public static class ProjectContent
{
private static readonly FramePhotos NoFrames = new([]);
///
/// The portable form of , whose positions name the frames
/// (by index). A position naming no frame of names nothing and goes. A project of a newer
/// Chronos is only made canonical: its positions are its own business.
///
/// The text is not a project object.
public static string ToPortable(string settingsJson, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(frames);
var canonical = Canonical(settingsJson);
if (FormatOf(canonical) > ProjectSettings.CurrentVersion) return canonical;
// With no frames there is nothing to name: a translation to no frames would keep the positions as they are.
var translated = frames.Count == 0 ? WithoutPositions(canonical) : ProjectSettings.TranslateFramePositions(canonical, frames, NoFrames);
return translated is null ? canonical : Canonical(translated);
}
///
public static string ToPortable(ProjectSettings settings, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(settings);
return ToPortable(settings.ToJson(), frames);
}
///
/// The settings of a portable project with its positions placed on : each pending frame whose
/// photo a frame holds becomes a position again; those whose photo is not there keep waiting.
///
/// The text is not a project object.
public static string Place(string portableJson, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(frames);
ArgumentNullException.ThrowIfNull(portableJson);
if (FormatOf(portableJson) > ProjectSettings.CurrentVersion) return portableJson;
return ProjectSettings.TranslateFramePositions(portableJson, null, frames) ?? portableJson;
}
///
/// The canonical text of a project: read (a newer Chronos's too, its unknown members kept) and written again, its
/// pending frames in a fixed order (by photo) and their capture times as wall-clock values.
///
/// The text is not a project object.
public static string Canonical(string json)
{
ArgumentNullException.ThrowIfNull(json);
ProjectSettings settings;
try
{
settings = ProjectSettings.FromJson(json, allowNewer: true);
}
catch (InvalidDataException ex)
{
throw new JsonException(ex.Message, ex);
}
if (settings.PendingFrames is { Count: > 0 } pending)
{
settings = settings with { PendingFrames = [.. pending.Select(Normalized).OrderBy(Key, StringComparer.Ordinal)] };
}
return settings.ToJson();
}
/// The SHA-256 (lower-case hex) of the UTF-8 bytes of : a project version's content hash.
public static string Hash(string text)
{
ArgumentNullException.ThrowIfNull(text);
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
}
/// Whether is the content hash of (any case).
public static bool Verifies(string text, string? hash) => hash is { Length: 64 } && string.Equals(Hash(text), hash, StringComparison.OrdinalIgnoreCase);
/// The settings format () a project's text declares; 1 when it says none or is not a project.
public static int FormatOf(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return ProjectSettings.CurrentVersion;
try
{
return JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is JsonObject project
&& project["version"] is JsonValue value && value.TryGetValue(out var version) && version > 0
? version
: ProjectSettings.CurrentVersion;
}
catch (Exception ex) when (ex is JsonException or ArgumentException)
{
return ProjectSettings.CurrentVersion;
}
}
///
/// A pending frame as the canonical text holds it: its capture time as a wall-clock value, and the frame its keyframes
/// were on left out (0: it is set again when the photo takes its place).
///
private static PendingFrame Normalized(PendingFrame frame) => frame with
{
CapturedAt = frame.CapturedAt is { } at ? DateTime.SpecifyKind(at, DateTimeKind.Unspecified) : null,
// Read from a hand-written entry without keyframes, the list is null.
Keyframes = frame.Keyframes is { Count: > 0 } keys ? [.. keys.Select(k => k with { Frame = 0 })] : [],
};
/// Order of pending frames in the canonical text: by hash, then capture time, size and which copy of the photo.
private static string Key(PendingFrame frame) => string.Create(CultureInfo.InvariantCulture,
$"{frame.Sha256?.ToLowerInvariant()}|{frame.CapturedAt?.Ticks:D20}|{frame.Size:D20}|{frame.Occurrence:D10}");
/// A project of a sequence without frames: its positions name nothing.
private static string? WithoutPositions(string json)
{
if (JsonNode.Parse(json) is not JsonObject project) return null;
var changed = false;
if (project["excludedFrames"] is JsonArray { Count: > 0 } excluded)
{
excluded.Clear();
changed = true;
}
if (project["heroFrame"] is not null)
{
project.Remove("heroFrame");
changed = true;
}
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray { Count: > 0 } keys)
{
keys.Clear();
changed = true;
}
return changed ? project.ToJsonString() : null;
}
}