using System.ComponentModel.DataAnnotations; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.Mvc.Rendering; using PlotLine.Data; using PlotLine.ViewModels; namespace PlotLine.Services.Context; public sealed class ContextCharacterEditForm { public int BookID{get;set;}public int SceneID{get;set;}public int CharacterID{get;set;} public string Field{get;set;}="";public string Fingerprint{get;set;}=""; [StringLength(4000)]public string? Value{get;set;} public string Label{get;set;}="";public string CharacterName{get;set;}=""; public IReadOnlyList Options{get;set;}=[]; } public sealed class ContextCharacterEditing(ICharacterService characters,IStoryContextService stories,ICharacterRepository repository, IWordCompanionRepository access,IBookRepository books,IProjectRepository projects,ICurrentUserService user,ContextWorkspaceNotifications notifications) { private static readonly SemaphoreSlim[] Locks=Enumerable.Range(0,64).Select(_=>new SemaphoreSlim(1,1)).ToArray(); private sealed record Frame(ContextCharacterEditForm Form,CharacterEditViewModel Character,SceneEditViewModel? Scene,PlotLine.Models.SceneCharacter? Appearance); private static string Hash(object value)=>Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value)))); public async Task Read(int bookId,int sceneId,int characterId,string field)=>(await Load(bookId,sceneId,characterId,field)).Form; private async Task Load(int bookId,int sceneId,int characterId,string field) { if(string.IsNullOrWhiteSpace(field))throw new ArgumentException("Choose a correction field."); var author=user.UserId??throw new UnauthorizedAccessException(); var structure=await access.GetBookStructureAsync(bookId,author)??throw new UnauthorizedAccessException(); var book=await books.GetAsync(bookId)??throw new UnauthorizedAccessException(); var project=await projects.GetForUserAsync(book.ProjectID,author); if(!ContextEditPolicy.CanEdit(project))throw new UnauthorizedAccessException(); var reference=field=="life-status"?await characters.GetReferenceCharacterAsync(characterId):null; var character=field=="life-status"?(reference==null?throw new UnauthorizedAccessException():new CharacterEditViewModel{CharacterID=reference.CharacterID,ProjectID=reference.ProjectID,CharacterName=reference.CharacterName,IsDeceased=reference.IsDeceased,OriginalIsDeceased=reference.IsDeceased,LifeStatusProvided=true}):await characters.GetEditCharacterAsync(characterId)??throw new UnauthorizedAccessException(); if(character.ProjectID!=book.ProjectID)throw new UnauthorizedAccessException(); SceneEditViewModel? scene=null;PlotLine.Models.SceneCharacter? appearance=null; var labels=new Dictionary{{"life-status","Life status · global author reference"},{"classification","Character classification"},{"description","Character description"},{"emotion","Emotional state in this scene"},{"condition","Physical condition in this scene"},{"location","Recorded location in this scene"}}; IReadOnlyList aliases=field=="life-status"?[]:await repository.ListAliasesAsync(characterId); var selectedAlias=field.StartsWith("alias:")&&int.TryParse(field[6..],out var aliasId)?aliases.SingleOrDefault(a=>a.CharacterAliasID==aliasId):null; labels["name"]="Canonical name (previous spelling retained as an alias)";labels["alias-add"]="Add one alias"; if(selectedAlias!=null)labels[field]="Correct alias (clear to remove this alias)"; if(!labels.ContainsKey(field))throw new ArgumentException("Unsupported correction."); if(sceneId>0&&!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))throw new UnauthorizedAccessException(); if(field is "emotion" or "condition" or "location"){ scene=(await stories.GetForSceneAsync(sceneId,book.ProjectID,bookId,forWriting:true,includeNarrative:false))?.Scene??throw new UnauthorizedAccessException(); appearance=scene.SceneCharacters.SingleOrDefault(a=>a.CharacterID==characterId)??throw new UnauthorizedAccessException(); } var value=field switch{"classification"=>character.CharacterImportance?.ToString(),"description"=>character.DefaultDescription,"emotion"=>appearance?.EmotionalState,"condition"=>appearance?.PhysicalCondition,"location"=>appearance?.LocationID?.ToString(),"life-status"=>character.IsDeceased?.ToString().ToLowerInvariant(),"name"=>character.CharacterName,"alias-add"=>"",_=>selectedAlias?.Alias}; IReadOnlyList options=[]; if(field=="life-status")options=[new("Unrecorded",""),new("Living · author reference","false"),new("Deceased · author reference","true")]; if(field=="classification"){ var choices=new List{new("Unclassified",""),new("Major · author choice","10"),new("Supporting","6"),new("Minor","2")}; if(value!=null&&choices.All(c=>c.Value!=value))choices.Add(new("Current recorded classification ("+value+")",value));options=choices; } if(field=="location")options=[new("No recorded location",""),..scene!.LocationOptions]; var hash=appearance!=null?Hash(new{appearance.SceneCharacterID,appearance.SceneID,appearance.CharacterID,appearance.RoleInSceneTypeID,appearance.PresenceTypeID,appearance.LocationID,appearance.EntryLocationID,appearance.ExitLocationID,appearance.AppearanceNotes,appearance.OutfitDescription,appearance.EmotionalState,appearance.PhysicalCondition,appearance.KnowledgeNotes}):Hash(new{character.CharacterID,character.CharacterName,character.Aliases,character.CharacterImportance,character.DefaultDescription,character.SexValueID,character.Sex,character.BirthDate,character.IsDeceased,character.AgeAtSeriesStart,character.Height,character.EyeColour,character.ShowInQuickAddBar,character.ImagePath,character.ThumbnailPath,AliasRecords=aliases}); return new(new(){BookID=bookId,SceneID=sceneId,CharacterID=characterId,Field=field,Value=value,Label=labels[field],CharacterName=character.CharacterName,Fingerprint=hash,Options=options},character,scene,appearance); } public async Task Save(ContextCharacterEditForm input) { var mutex=Locks[(input.CharacterID&int.MaxValue)%Locks.Length];await mutex.WaitAsync(); try{ var frame=await Load(input.BookID,input.SceneID,input.CharacterID,input.Field); if(frame.Form.Fingerprint!=input.Fingerprint)throw new InvalidOperationException("This record changed in another window. Your draft is retained; cancel and reopen to load current values."); if(input.Value?.Length>4000)throw new ArgumentException("Use 4,000 characters or fewer."); if(input.Field=="name"||input.Field.StartsWith("alias")){ var value=input.Value?.Trim()??""; if(value.Length>200)throw new ArgumentException("Use 200 characters or fewer for a name or alias."); if(input.Field=="name"){ if(value.Length==0)throw new ArgumentException("Enter the canonical name."); frame.Character.Aliases=frame.Character.Aliases.Append(frame.Character.CharacterName).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); frame.Character.CharacterName=value;await characters.SaveCharacterAsync(frame.Character); }else{ var aliases=await repository.ListAliasesAsync(input.CharacterID); if(input.Field=="alias-add"){ if(value.Length==0)throw new ArgumentException("Enter an alias."); if(aliases.Count>=50)throw new ArgumentException("Review the full character editor before adding more than 50 aliases."); if(aliases.Any(a=>string.Equals(a.Alias,value,StringComparison.OrdinalIgnoreCase)))throw new ArgumentException("This character already has that alias."); await repository.AddAliasAsync(input.CharacterID,value,null); }else{ var alias=aliases.Single(a=>a.CharacterAliasID==int.Parse(input.Field[6..])); if(string.Equals(alias.Alias,frame.Character.CharacterName,StringComparison.OrdinalIgnoreCase))throw new ArgumentException("Correct the canonical name using its own action."); if(value.Length==0)await repository.DeleteAliasAsync(alias.CharacterAliasID); else{ if(aliases.Any(a=>a.CharacterAliasID!=alias.CharacterAliasID&&string.Equals(a.Alias,value,StringComparison.OrdinalIgnoreCase)))throw new ArgumentException("This character already has that alias."); await repository.UpdateAliasAsync(alias.CharacterAliasID,value,alias.SortOrder); } } } }else if(input.Field=="classification"){ int? importance=null;if(!string.IsNullOrWhiteSpace(input.Value)){if(!int.TryParse(input.Value,out var parsed)||(!new[]{2,6,10}.Contains(parsed)&&parsed!=frame.Character.CharacterImportance))throw new ArgumentException("Choose a recorded classification.");importance=parsed;} frame.Character.CharacterImportance=importance;await characters.SaveCharacterAsync(frame.Character); }else if(input.Field=="life-status"){ if(!frame.Form.Options.Any(o=>o.Value==(input.Value??"")))throw new ArgumentException("Choose Unrecorded, Living or Deceased."); await characters.SaveLifeStatusAsync(input.CharacterID,string.IsNullOrEmpty(input.Value)?null:bool.Parse(input.Value),frame.Character.IsDeceased); }else if(input.Field=="description"){frame.Character.DefaultDescription=input.Value;await characters.SaveCharacterAsync(frame.Character);} else{ var a=frame.Appearance!;var edit=new SceneCharacterEditViewModel{SceneCharacterID=a.SceneCharacterID,SceneID=a.SceneID,CharacterID=a.CharacterID,RoleInSceneTypeID=a.RoleInSceneTypeID,PresenceTypeID=a.PresenceTypeID,LocationID=a.LocationID,EntryLocationID=a.EntryLocationID,ExitLocationID=a.ExitLocationID,AppearanceNotes=a.AppearanceNotes,OutfitDescription=a.OutfitDescription,PhysicalCondition=a.PhysicalCondition,EmotionalState=a.EmotionalState,KnowledgeNotes=a.KnowledgeNotes}; if(input.Field=="emotion")edit.EmotionalState=input.Value; if(input.Field=="condition")edit.PhysicalCondition=input.Value; if(input.Field=="location"){ if(!string.IsNullOrWhiteSpace(input.Value)&&!frame.Form.Options.Any(o=>o.Value==input.Value))throw new ArgumentException("Choose a location from this project."); edit.LocationID=string.IsNullOrWhiteSpace(input.Value)?null:int.Parse(input.Value); } await characters.UpdateSceneCharacterAsync(edit); } await notifications.Invalidate(user.UserId!.Value,frame.Appearance==null?null:input.BookID,projectId:frame.Character.ProjectID); }finally{mutex.Release();} } }