using System.Collections.Frozen; using System.Diagnostics.CodeAnalysis; namespace AIStudio.Tools.DocumentSegments; /// /// What became of the segments of a document, found by the text of each segment. /// /// /// The results stay unchanged once created, so that an assistant can keep them while the user saves the /// document, maybe more than once. A segment without letters needs no result: it stays as it is anyway. /// public sealed class SegmentResults { private readonly FrozenDictionary outcomes; /// /// Creates the results. /// /// What became of each segment, by its Key. public SegmentResults(IReadOnlyDictionary outcomes) => this.outcomes = outcomes.ToFrozenDictionary(StringComparer.Ordinal); /// /// How many distinct segments ended in the given way. /// /// What became of the segments. public int CountOf(SegmentStatus status) => this.outcomes.Values.Count(outcome => outcome.Status == status); /// /// How many distinct segments got a new text which differs from their source. /// /// /// A model may return a text as it is, e.g., a correction which found no mistake: such a segment counts /// as transformed, but not as changed. /// public int CountChanged() => this.outcomes.Count(entry => entry.Value is { Status: SegmentStatus.TRANSFORMED, Text: { } text } && !string.Equals(text, entry.Key, StringComparison.Ordinal)); /// /// Whether these results know what became of a segment. /// /// /// A format checks this for every segment before it writes anything: a segment with letters which the /// results do not know means that the document changed since it was read. /// /// A segment of the document. public bool Covers(DocumentSegment segment) => !segment.HasWords || this.outcomes.ContainsKey(segment.Key); /// /// Gets the new text of a segment, when a model worked on it. /// /// A segment of the document. /// The new text with tags, or null when the segment stays as it is. /// Whether the segment has a new text. public bool TryGetText(DocumentSegment segment, [NotNullWhen(true)] out string? text) { if (this.outcomes.TryGetValue(segment.Key, out var outcome) && outcome is { Status: SegmentStatus.TRANSFORMED, Text: { } newText }) { text = newText; return true; } text = null; return false; } }