using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Protocol;
using SequenceFrames = Chronos.Data.Processing.SequenceFrames;
namespace Chronos.Data.Sync;
///
/// The frame positions of settings crossing between a local copy and its server sequence (exclusions, hero, camera
/// keyframes; BRIEF §5, §14.5). Each copy numbers its frames in capture order, and the two may hold different photos
/// while originals are still to travel, so settings are translated by photo on the way: the server's are moved to this
/// copy's frames before they are compared or applied, and this copy's to the server's frames as
/// lists them before they are sent. A position on a photo the receiving copy lacks waits
/// there as a pending frame and takes its place when the photo arrives ().
/// Positions are only ever translated against the frames they name: this copy's row is read with its frames as one
/// state (frames inserted here move the row's positions in the same step), and a manifest whose frames mix two orders
/// is not translated at all.
///
internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid localId, SequenceManifest manifest)
{
/// Times this copy's frames are listed again when an insertion lands while they are read.
private const int Attempts = 3;
/// The manifest's frames by hash, and with their capture times once fetched.
private FramePhotos? _hashed, _timed;
/// The server's frames version the translation to the server's frames is made against.
public int ServerFrames => manifest.FramesVersion;
///
/// The server's settings with their positions on this copy's frames as they are now, with this copy's row at those
/// frames; null when that row is no longer at (an edit was saved here since), or
/// either copy's frames cannot be read as one state now (the next comparison translates again).
///
public async Task ToLocalAsync(string? settingsJson, int settingsVersion, CancellationToken cancellationToken)
{
if (!ProjectSettings.NamesFrames(settingsJson))
return await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is { } row && row.SettingsVersion == settingsVersion
? new TranslatedSettings(row, settingsJson)
: null;
if (await LocalAsync(cancellationToken).ConfigureAwait(false) is not { } local || local.Row.SettingsVersion != settingsVersion) return null;
if (await ServerAsync(local.Frames, cancellationToken).ConfigureAwait(false) is not { } server) return null;
return new TranslatedSettings(local.Row, ProjectSettings.TranslateFramePositions(settingsJson!, server, local.Frames) ?? settingsJson);
}
///
/// This copy's settings at with their positions on the server's frames, with the
/// row they were taken from: frames inserted here since the copy was read moved its positions without a new settings
/// version, so the row is read again with its frames. Null when the row is at another settings version (an edit was
/// saved since), or either copy's frames cannot be read as one state now.
///
public async Task ToServerAsync(int settingsVersion, CancellationToken cancellationToken)
{
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } row || row.SettingsVersion != settingsVersion) return null;
// Positions cannot appear in a project that names no frame: an insertion only moves those it has.
if (!ProjectSettings.NamesFrames(row.SettingsJson)) return new TranslatedSettings(row, row.SettingsJson);
if (await LocalAsync(cancellationToken).ConfigureAwait(false) is not { } local || local.Row.SettingsVersion != settingsVersion) return null;
if (await ServerAsync(local.Frames, cancellationToken).ConfigureAwait(false) is not { } server) return null;
var settings = local.Row.SettingsJson;
return new TranslatedSettings(local.Row, settings is null ? null : ProjectSettings.TranslateFramePositions(settings, local.Frames, server) ?? settings);
}
///
/// This copy's row and frames as one state: the frames are listed between two reads of the row that find the same
/// frames version (an insertion renumbers the frames and moves the row's positions in one transaction, and bumps the
/// version). Null when the sequence is gone or an insertion lands during every attempt.
///
private async Task LocalAsync(CancellationToken cancellationToken)
{
for (var attempt = 0; attempt < Attempts; attempt++)
{
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } before) return null;
var frames = await SequenceFrames.ListAsync(db, localId, cancellationToken).ConfigureAwait(false);
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } after) return null;
if (after.FramesVersion == before.FramesVersion)
return new LocalState(after, new FramePhotos(frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))));
}
return null;
}
///
/// The server's frames from the manifest; null when they do not read as one frame list (an index given twice, or
/// not the indices 0…n-1: pages read across an insertion). Their capture times are fetched unless both copies hold
/// the same hashed photos at the same places: a frame is matched by size and capture time when either side has not
/// hashed it, and a position parked on a server photo always names its capture time, so the same project reads the
/// same whichever side hashed what.
///
private async Task ServerAsync(FramePhotos local, CancellationToken cancellationToken)
{
if (_hashed is null)
{
if (!OneList(manifest.Frames)) return null;
_hashed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, null))));
}
if (_hashed.SameAs(local)) return _hashed;
if (_timed is null)
{
var captured = (await remote.ListFramesAsync(manifest.SequenceId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
_timed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id)))));
}
return _timed;
}
/// Each frame once, at the indices 0…n-1 a sequence's frames always take.
private static bool OneList(IReadOnlyList frames)
{
var seen = new bool[frames.Count];
var ids = new HashSet();
foreach (var frame in frames)
{
if ((uint)frame.Index >= (uint)seen.Length || seen[frame.Index] || !ids.Add(frame.Id)) return false;
seen[frame.Index] = true;
}
return true;
}
private sealed record LocalState(Sequence Row, FramePhotos Frames);
}
///
/// Settings translated by , with this copy's row at the frames their positions were
/// translated to or from (its own settings may have been moved since it was first read).
///
internal sealed record TranslatedSettings(Sequence Local, string? SettingsJson);