using System.Data; using System.Text.Json; using Dapper; using PlotLine.Data; using PlotLine.Models; namespace PlotLine.Services.Context; public sealed record ContextThreadRow(int PlotThreadID, int PlotLineID, string Title, string PlotLineName, bool Linked, IReadOnlyList PreviousScenes); public sealed record ContextThreadsPanel(SpatialScope Scope, IReadOnlyList Threads); public sealed record ContextThreadSelection(int BookID, int SceneID, int[] ThreadIDs); public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRepository workspace, ISqlConnectionFactory connections, ICurrentUserService user, ContextWorkspaceNotifications notifications) { public async Task Read(int book, int scene) { var scope = await spatial.Scope(book, scene); var data = await workspace.GetAsync(scope.ProjectID, book, null); using var db = connections.CreateConnection(); var links = await db.QueryAsync("dbo.SceneThread_ListByBook", new { BookID = book, UserID = user.UserId!.Value }, commandType: CommandType.StoredProcedure); return Build(scope, data, links); } public static ContextThreadsPanel Build(SpatialScope scope, PlotLineWorkspaceData data, IEnumerable links) { var scenes = data.AttributionScenes.Where(s => s.BookID == scope.BookID).ToDictionary(s => s.SceneID); if (!scenes.TryGetValue(scope.SceneID, out var current)) throw new ArgumentException("Scene order is unavailable."); var lines = data.PlotLines.Where(l => l.ProjectID == scope.ProjectID && (l.BookID == null || l.BookID == scope.BookID)).ToDictionary(l => l.PlotLineID); var associations = links.Select(l => (l.PlotThreadID, l.SceneID)) .Concat(data.Contributions.Where(c => c.BookID == scope.BookID).Select(c => (c.PlotThreadID, c.SceneID))) .ToHashSet(); // Established milestones are authoritative associations too. A planned resolution // alone is a future intention, not a scene where the thread has been picked up. foreach (var thread in data.Threads) { if (thread.IntroducedSceneID is int introduced) associations.Add((thread.PlotThreadID, introduced)); if (thread.ActualResolutionSceneID is int resolved) associations.Add((thread.PlotThreadID, resolved)); } var rows = data.Threads.Where(t => lines.ContainsKey(t.PlotLineID)).Select(t => new ContextThreadRow( t.PlotThreadID, t.PlotLineID, t.ThreadTitle, lines[t.PlotLineID].PlotLineName, associations.Contains((t.PlotThreadID, scope.SceneID)), scenes.Values.Where(s => s.NarrativeOrder < current.NarrativeOrder && associations.Contains((t.PlotThreadID, s.SceneID))) .OrderBy(s => s.NarrativeOrder).ToArray())).OrderBy(t => t.PlotLineName).ThenBy(t => t.Title).ToArray(); return new(scope, rows); } public async Task Add(ContextThreadSelection input) { if (input.ThreadIDs is not { Length: > 0 and <= 200 } || input.ThreadIDs.Any(id => id <= 0)) throw new ArgumentException("Choose between 1 and 200 threads."); using var db = connections.CreateConnection(); var project = await db.QuerySingleAsync("dbo.SceneThread_Add", new { input.BookID, input.SceneID, UserID = user.UserId ?? throw new UnauthorizedAccessException(), ThreadIDs = JsonSerializer.Serialize(input.ThreadIDs.Distinct()) }, commandType: CommandType.StoredProcedure); // Any earlier scene can affect history in all later scenes of the same book. await notifications.Invalidate(user.UserId!.Value, projectId: project, bookId: input.BookID, kind: "threads"); } }