namespace Titano.App.Settings;
///
/// Orders Settings › Archive's reads of the open archive's settings (its archive.json and index row) against the edits
/// written into them. A read that overlapped a write may hold the file as it was before the edit (a share waking up
/// answers late, and reads take no settings lease): showing it would undo the edit on the rows and in this PC's defaults
/// while the archive keeps it. Such a read is not shown (): its reader waits until no edit is being
/// written () and reads again, so a read is done only once the rows show what the archive holds.
/// Used from the interface thread only.
///
public sealed class ArchiveReadGate
{
/// The token of a read begun while an edit was being written: never current.
private const int Overlapped = -1;
private int _begun;
private int _writing;
private TaskCompletionSource? _written;
/// An edit starts being written into the archive.
public void BeginWrite()
{
_begun++;
_writing++;
}
/// The edit was written, or failed. When it was the last one being written, the reads waiting for it go on.
public void EndWrite()
{
if (_writing == 0) throw new InvalidOperationException("No edit is being written.");
if (--_writing > 0) return;
var written = _written;
_written = null;
written?.SetResult();
}
/// A read starts; its token tells which edits it may have missed.
public int BeginRead() => _writing > 0 ? Overlapped : _begun;
///
/// Whether what a read begun with found may be shown: no edit was being written when it began
/// and none began since. When it may not, its reader awaits and reads again.
///
public bool IsCurrent(int token) => token == _begun;
///
/// Done once no edit is being written: at once when none is, else when the last one ends. Its continuations run after
/// returns, never inside it.
///
public Task WrittenAsync() =>
_writing == 0 ? Task.CompletedTask : (_written ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task;
}