using PlotLine.Models; using PlotLine.ViewModels; namespace PlotLine.Services; // Read-only projection of the canonical workspace data, scoped to one book. public static class WritingContextPlotLines { public static PlotLineWorkspaceViewModel Build(PlotLineWorkspaceData data, int projectId, int bookId) { var scenes = data.AttributionScenes.Where(s => s.BookID == bookId).OrderBy(s => s.NarrativeOrder).ToArray(); var sceneIds = scenes.Select(s => s.SceneID).ToHashSet(); var lines = data.PlotLines.Where(l => l.ProjectID == projectId && (l.BookID == null || l.BookID == bookId)).ToArray(); foreach (var line in lines) line.Colour = PlotLineColours.ForLine(line.PlotLineID, line.Colour); var lineIds = lines.Select(l => l.PlotLineID).ToHashSet(); var events = data.Contributions.Where(c => c.BookID == bookId && sceneIds.Contains(c.SceneID) && lineIds.Contains(c.PlotLineID)).ToArray(); var memberships = events.GroupBy(c => c.SceneID).ToDictionary(g => g.Key, g => PlotLineWorkspaceComposer.ComposeMemberships(data, g).ToDictionary(m => m.PlotLineID)); void Associate(int? sceneId, int lineId) { if (sceneId is not int id || !sceneIds.Contains(id) || !lineIds.Contains(lineId)) return; if (!memberships.TryGetValue(id, out var byLine)) memberships[id] = byLine = []; if (!byLine.ContainsKey(lineId)) { var line = lines.First(l => l.PlotLineID == lineId); byLine[lineId] = new() { PlotLineID = lineId, PlotLineName = line.PlotLineName, Colour = line.Colour }; } } // Saved thread milestones and cross-line targets are associations, not invented developments. foreach (var thread in data.Threads) { Associate(thread.IntroducedSceneID, thread.PlotLineID); Associate(thread.PlannedResolutionSceneID, thread.PlotLineID); Associate(thread.ActualResolutionSceneID, thread.PlotLineID); } var eventScenes = events.ToDictionary(e => e.ThreadEventID, e => e.SceneID); foreach (var target in data.Targets) if (eventScenes.TryGetValue(target.ThreadEventID, out var scene)) Associate(scene, target.TargetPlotLineID); return new() { Project = new() { ProjectID = projectId }, SelectedBookID = bookId, AssociationScenes = scenes, PlotLines = lines.Select(l => new PlotLineWorkspaceLineViewModel { Line = l }).ToArray(), Scenes = scenes.Where(s => memberships.ContainsKey(s.SceneID)).Select(s => new PlotLineWorkspaceSceneViewModel { SceneID = s.SceneID, NarrativeOrder = s.NarrativeOrder, ChapterNumber = s.ChapterNumber, SceneNumber = s.SceneNumber, SceneTitle = s.SceneTitle, Memberships = memberships[s.SceneID].Values.ToArray() }).ToArray() }; } }