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 portable text with each pending frame whose photo hold named as they hold it now: an
/// encoding a conversion replaced by the one the frame holds (, also its undo), a photo parked
/// before it was hashed by its SHA-256, size and capture time, and which copy of that photo it is among the frames
/// holding it under that name (a photo of a burst told apart by its order while unhashed is unique once hashed). Entries
/// that name one photo once renamed become one (). The same choices on the same photos then read as
/// the same text (), whichever encoding or hashing state they were saved against; a placement
/// finds the same frames either way. Canonical when anything is renamed or folded; the text as it is otherwise, and for
/// a newer format.
///
/// The text is not a project object.
public static string Rebind(string portableJson, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(portableJson);
ArgumentNullException.ThrowIfNull(frames);
return Renamed(portableJson, frames, hashedOnly: true);
}
///
/// The portable text with each pending frame whose photo hold named as the frame holding it is,
/// hashed or not, which copy of it included: what the text places on these frames, read so to compare two texts only
/// (). Unlike , a SHA-256 the frames do not know yet (the photo hashed where
/// the text was saved, not when the frames were copied) gives way to the frame's size and capture time, so a text saved
/// on hashed frames and one saved on frames not hashed yet read alike. Always canonical.
///
private static string Bound(string portableJson, FramePhotos frames) => Canonical(Renamed(portableJson, frames, hashedOnly: false));
/// (: only onto frames that are hashed), else 's renaming.
private static string Renamed(string portableJson, FramePhotos frames, bool hashedOnly)
{
if (frames.Count == 0 || !portableJson.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)) return portableJson;
if (FormatOf(portableJson) > ProjectSettings.CurrentVersion) return portableJson;
if (JsonNode.Parse(portableJson, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is not JsonObject project
|| project["pendingFrames"] is not JsonArray pending) return portableJson;
var renamed = false;
foreach (var entry in pending.OfType())
{
var sha = entry["sha256"] is JsonValue s && s.TryGetValue(out var text) ? text : null;
var size = entry["size"] is JsonValue z && z.TryGetValue(out var bytes) ? bytes : -1;
DateTime? captured = entry["capturedAt"] is JsonValue t && t.TryGetValue(out var time) ? time : null;
if (string.IsNullOrEmpty(sha) && (captured is null || size < 0)) continue;
var occurrence = entry["occurrence"] is JsonValue o && o.TryGetValue(out var n) && n > 0 ? n : 0;
// Only a frame that is hashed names a photo better than the entry does (to keep; to compare, any frame does).
if (frames.IndexOf(new FramePhoto(sha, size, captured), occurrence) is not { } at || frames[at] is not { } held || (hashedOnly && !held.IsHashed)) continue;
// The copy a placement looks for under the new name: among the frames holding that SHA-256, not those of that size and time.
var copy = frames.Occurrence(at);
var sameTime = held.CapturedAt is { } heldAt
? captured is { } entryAt && FramePhoto.Millisecond(heldAt) == FramePhoto.Millisecond(entryAt)
: captured is null;
if (string.Equals(held.Sha256 ?? string.Empty, sha ?? string.Empty, StringComparison.OrdinalIgnoreCase) && held.Size == size && sameTime
&& copy == occurrence) continue;
if (held.IsHashed) entry["sha256"] = held.Sha256!.ToLowerInvariant();
else entry.Remove("sha256");
entry["size"] = held.Size;
if (held.CapturedAt is { } heldTime) entry["capturedAt"] = heldTime;
else entry.Remove("capturedAt");
if (copy > 0) entry["occurrence"] = copy;
else entry.Remove("occurrence");
renamed = true;
}
renamed |= FoldAlike(pending);
return renamed ? Canonical(project.ToJsonString()) : portableJson;
}
///
/// The photo a pending entry names and which copy of it: "sha:<sha-256>#<occurrence>", or
/// "photo:<size>@<capture ticks>#<occurrence>" for a photo not hashed; null for an entry naming no photo.
/// Entries of one key are one photo's positions ().
///
public static string? PhotoKey(JsonNode? entry)
{
if (entry is not JsonObject e) return null;
var occurrence = e["occurrence"] is JsonValue o && o.TryGetValue(out var n) ? n : 0;
if (e["sha256"] is JsonValue s && s.TryGetValue(out var sha) && sha.Length > 0)
return string.Create(CultureInfo.InvariantCulture, $"sha:{sha.ToLowerInvariant()}#{occurrence}");
var size = e["size"] is JsonValue z && z.TryGetValue(out var bytes) ? bytes : 0;
return e["capturedAt"] is JsonValue c && c.TryGetValue(out var at)
? string.Create(CultureInfo.InvariantCulture, $"photo:{size}@{at.Ticks}#{occurrence}")
: null;
}
///
/// Folds into , two pending entries of one photo (saved under two names,
/// alike since): excluded or hero when either is, the keyframes of both (each once), and the members this Chronos does not
/// know of both (those of where both have one). Nothing either held is dropped.
///
public static void Fold(JsonObject into, JsonObject entry)
{
ArgumentNullException.ThrowIfNull(into);
ArgumentNullException.ThrowIfNull(entry);
if (Flag(entry, "excluded")) into["excluded"] = true;
if (Flag(entry, "hero")) into["hero"] = true;
if (entry["keyframes"] is JsonArray { Count: > 0 } keys)
{
if (into["keyframes"] is not JsonArray mine) into["keyframes"] = mine = new JsonArray();
foreach (var key in keys.ToList())
{
if (!mine.Any(k => JsonNode.DeepEquals(k, key))) mine.Add(key?.DeepClone());
}
}
foreach (var (name, value) in entry.ToList())
{
if (!ProjectSettings.PendingMembers.Contains(name) && !into.ContainsKey(name)) into[name] = value?.DeepClone();
}
}
/// Folds the pending entries naming one photo into the first of them (); whether any were.
private static bool FoldAlike(JsonArray pending)
{
var first = new Dictionary(StringComparer.Ordinal);
var folded = new List();
foreach (var entry in pending.OfType())
{
if (PhotoKey(entry) is not { } key) continue;
if (first.TryGetValue(key, out var into))
{
Fold(into, entry);
folded.Add(entry);
}
else
{
first[key] = entry;
}
}
foreach (var entry in folded) pending.Remove(entry);
return folded.Count > 0;
}
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue(out var set) && set;
///
/// Whether two portable texts hold the same choices on the frames of : the same text, or the
/// same once their pending frames are named as the frames hold their photos now (), or as the frame
/// each lands on is named, hashed or not (): a version saved where a photo was hashed after these
/// frames were copied holds what a working state saved on them does, so it reads neither as a change nor as one to save.
///
/// A text is not a project object.
public static bool SameChoices(string portable, string other, FramePhotos frames)
{
ArgumentNullException.ThrowIfNull(portable);
ArgumentNullException.ThrowIfNull(other);
ArgumentNullException.ThrowIfNull(frames);
if (portable == other) return true;
if (frames.Count == 0) return false;
return Rebind(portable, frames) == Rebind(other, frames) || (frames.HasUnhashed && Bound(portable, frames) == Bound(other, frames));
}
///
/// 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;
}
}