using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using DataServer.Data; using DataServer.Data.Entities; using DataServer.Data.Enums; using System.Text.Json; namespace GameServices.Admin.Pages.Npcs; public class EditModel : AdminPageModel { private readonly GameDbContext _db; public EditModel(GameDbContext db) { _db = db; } [BindProperty] public DungeonNpcDefinition Npc { get; set; } = new(); public List LootTables { get; set; } = new(); public List Shops { get; set; } = new(); public List DialogTrees { get; set; } = new(); public List ResistanceTypes { get; set; } = new(); public List AllAbilities { get; set; } = new(); public List AllAnimations { get; set; } = new(); public List SelectedAbilityIds { get; set; } = new(); public List SelectedAnimations { get; set; } = new(); public bool IsNew => Npc.Id == 0; public string? Message { get; set; } public bool IsError { get; set; } public class NpcAnimationSelection { public int AnimationDefinitionId { get; set; } public string? OverrideKey { get; set; } public bool IsEnabled { get; set; } = true; } public async Task OnGetAsync(int? id) { await LoadSelectionsAsync(); if (id.HasValue) { var npc = await _db.DungeonNpcDefinitions.FirstOrDefaultAsync(n => n.Id == id.Value); if (npc != null) { Npc = npc; ParseNpcJsonFields(); return; } } Npc = new DungeonNpcDefinition { Name = "", Key = "", Description = "", Level = 1, IsEnabled = true, IsKillable = true, CanShop = false, HasDialog = false, CanWander = true, BehaviorMode = NpcBehaviorMode.Wander, OnAttackBehavior = NpcOnAttackBehavior.FightBack, MaxHealth = 100, AttackPower = 10, Defense = 5, Strength = 5, Dexterity = 5, Intelligence = 5, Wisdom = 5, Endurance = 5, ResistancesJson = "{}", AbilityDefinitionIdsJson = "[]", TintColor = "#ffffff", Scale = 1f, WanderRadiusPx = 96f, WanderIntervalSeconds = 2.5f }; ParseNpcJsonFields(); } public async Task OnPostAsync() { await LoadSelectionsAsync(); Npc.IsEnabled = Request.Form.ContainsKey("Npc.IsEnabled"); Npc.IsKillable = Request.Form.ContainsKey("Npc.IsKillable"); Npc.CanShop = Request.Form.ContainsKey("Npc.CanShop"); Npc.HasDialog = Request.Form.ContainsKey("Npc.HasDialog"); Npc.CanWander = Request.Form.ContainsKey("Npc.CanWander"); Npc.Name = (Npc.Name ?? "").Trim(); Npc.Key = (Npc.Key ?? "").Trim(); Npc.Description ??= ""; Npc.TintColor = string.IsNullOrWhiteSpace(Npc.TintColor) ? "#ffffff" : Npc.TintColor.Trim(); ParseAndSetResistancesFromForm(); ParseAndSetAbilityIdsFromForm(); ParseAndSetAnimationsFromForm(); if (string.IsNullOrWhiteSpace(Npc.Name)) { IsError = true; Message = "Name is required."; ParseNpcJsonFields(); return Page(); } if (string.IsNullOrWhiteSpace(Npc.Key)) { Npc.Key = Npc.Name.ToLowerInvariant().Replace(" ", "_"); } try { if (Npc.Id == 0) { Npc.CreatedAt = DateTime.UtcNow; Npc.UpdatedAt = DateTime.UtcNow; _db.DungeonNpcDefinitions.Add(Npc); await _db.SaveChangesAsync(); return RedirectToPage("/Npcs/Edit", new { id = Npc.Id }); } var existing = await _db.DungeonNpcDefinitions.FirstOrDefaultAsync(n => n.Id == Npc.Id); if (existing == null) { IsError = true; Message = "NPC not found."; ParseNpcJsonFields(); return Page(); } existing.Name = Npc.Name; existing.Key = Npc.Key; existing.Description = Npc.Description; existing.Level = Npc.Level; existing.IsEnabled = Npc.IsEnabled; existing.IsKillable = Npc.IsKillable; existing.CanShop = Npc.CanShop; existing.HasDialog = Npc.HasDialog; existing.CanWander = Npc.CanWander; existing.BehaviorMode = Npc.BehaviorMode; existing.OnAttackBehavior = Npc.OnAttackBehavior; existing.MaxHealth = Npc.MaxHealth; existing.AttackPower = Npc.AttackPower; existing.Defense = Npc.Defense; existing.Strength = Npc.Strength; existing.Dexterity = Npc.Dexterity; existing.Intelligence = Npc.Intelligence; existing.Wisdom = Npc.Wisdom; existing.Endurance = Npc.Endurance; existing.ResistancesJson = Npc.ResistancesJson; existing.AbilityDefinitionIdsJson = Npc.AbilityDefinitionIdsJson; existing.SpriteConfigJson = string.IsNullOrWhiteSpace(Npc.SpriteConfigJson) ? null : Npc.SpriteConfigJson; existing.TintColor = Npc.TintColor; existing.Scale = Npc.Scale; existing.WanderRadiusPx = Npc.WanderRadiusPx; existing.WanderIntervalSeconds = Npc.WanderIntervalSeconds; existing.LootTableId = Npc.LootTableId; existing.ShopId = Npc.ShopId; existing.DialogTreeId = Npc.DialogTreeId; existing.UpdatedAt = DateTime.UtcNow; await _db.SaveChangesAsync(); Npc = existing; ParseNpcJsonFields(); Message = "Changes saved successfully."; } catch (Exception ex) { IsError = true; Message = $"Error: {ex.Message}"; ParseNpcJsonFields(); } return Page(); } private async Task LoadSelectionsAsync() { LootTables = await _db.DungeonLootTables .Where(l => l.IsEnabled) .OrderBy(l => l.Name) .ToListAsync(); Shops = await _db.DungeonNpcShops .Where(s => s.IsEnabled) .OrderBy(s => s.Name) .ToListAsync(); DialogTrees = await _db.DungeonNpcDialogTrees .Where(d => d.IsEnabled) .OrderBy(d => d.Name) .ToListAsync(); ResistanceTypes = await _db.DamageResistanceTypes .Where(r => r.IsEnabled) .OrderBy(r => r.SortOrder) .ToListAsync(); AllAbilities = await _db.MobAbilityDefinitions .Where(a => a.IsEnabled) .OrderBy(a => a.Name) .ToListAsync(); AllAnimations = await _db.MobAnimationDefinitions .Include(a => a.SpriteSheet) .Where(a => a.IsEnabled) .Where(a => a.SpriteSheet != null && a.SpriteSheet.IsEnabled) .OrderBy(a => a.SpriteSheet!.Name) .ThenBy(a => a.Key) .ToListAsync(); } private void ParseNpcJsonFields() { try { var resistanceMap = JsonSerializer.Deserialize>(Npc.ResistancesJson ?? "{}") ?? new(); Npc.ResistancesJson = JsonSerializer.Serialize(resistanceMap); } catch { Npc.ResistancesJson = "{}"; } try { SelectedAbilityIds = JsonSerializer.Deserialize>(Npc.AbilityDefinitionIdsJson ?? "[]") ?? new(); } catch { SelectedAbilityIds = new List(); Npc.AbilityDefinitionIdsJson = "[]"; } SelectedAnimations = ParseAnimationsFromSpriteConfig(Npc.SpriteConfigJson); } private List ParseAnimationsFromSpriteConfig(string? spriteConfigJson) { var selected = new List(); if (string.IsNullOrWhiteSpace(spriteConfigJson)) return selected; try { using var doc = JsonDocument.Parse(spriteConfigJson); var root = doc.RootElement; if (!root.TryGetProperty("sheets", out var sheetsElem) || !root.TryGetProperty("animations", out var animationsElem)) return selected; foreach (var animProp in animationsElem.EnumerateObject()) { var animKey = animProp.Name; var animObj = animProp.Value; if (!animObj.TryGetProperty("sheet", out var sheetRefElem)) continue; var sheetRef = sheetRefElem.GetString(); if (string.IsNullOrWhiteSpace(sheetRef)) continue; if (!sheetsElem.TryGetProperty(sheetRef, out var sheetObj)) continue; if (!sheetObj.TryGetProperty("path", out var pathElem)) continue; var path = pathElem.GetString(); if (string.IsNullOrWhiteSpace(path)) continue; var frames = animObj.TryGetProperty("frames", out var framesElem) ? framesElem.EnumerateArray().Select(x => x.GetInt32()).ToArray() : Array.Empty(); var fps = animObj.TryGetProperty("fps", out var fpsElem) ? fpsElem.GetSingle() : 8f; var loop = animObj.TryGetProperty("loop", out var loopElem) && loopElem.GetBoolean(); var flipX = animObj.TryGetProperty("flipX", out var flipXElem) && flipXElem.GetBoolean(); var flipY = animObj.TryGetProperty("flipY", out var flipYElem) && flipYElem.GetBoolean(); var match = AllAnimations.FirstOrDefault(a => { var sheet = a.SpriteSheet; if (sheet == null) return false; if (!string.Equals(sheet.CdnPath, path, StringComparison.OrdinalIgnoreCase)) return false; if (Math.Abs(a.Fps - fps) > 0.01f) return false; if (a.Loop != loop || a.FlipX != flipX || a.FlipY != flipY) return false; var aFrames = ParseFrameSequence(a.FrameSequence); return aFrames.SequenceEqual(frames); }); if (match == null) { match = AllAnimations.FirstOrDefault(a => a.SpriteSheet != null && string.Equals(a.Key, animKey, StringComparison.OrdinalIgnoreCase) && string.Equals(a.SpriteSheet.CdnPath, path, StringComparison.OrdinalIgnoreCase)); } if (match != null) { selected.Add(new NpcAnimationSelection { AnimationDefinitionId = match.Id, OverrideKey = string.Equals(animKey, match.Key, StringComparison.OrdinalIgnoreCase) ? null : animKey, IsEnabled = true }); } } } catch { // Keep empty if invalid JSON } return selected .GroupBy(x => new { x.AnimationDefinitionId, Key = (x.OverrideKey ?? "").Trim().ToLowerInvariant() }) .Select(g => g.First()) .ToList(); } private void ParseAndSetResistancesFromForm() { var map = new Dictionary(StringComparer.OrdinalIgnoreCase); var keys = Request.Form["resist_name[]"].ToArray(); var vals = Request.Form["resist_value[]"].ToArray(); for (var i = 0; i < keys.Length && i < vals.Length; i++) { var key = (keys[i] ?? "").Trim().ToLowerInvariant(); if (string.IsNullOrWhiteSpace(key)) continue; if (!float.TryParse(vals[i], out var val)) continue; map[key] = val; } Npc.ResistancesJson = JsonSerializer.Serialize(map); } private void ParseAndSetAbilityIdsFromForm() { var list = new List(); foreach (var raw in Request.Form["ability_ids[]"]) { if (int.TryParse(raw, out var id) && id > 0 && !list.Contains(id)) { list.Add(id); } } SelectedAbilityIds = list; Npc.AbilityDefinitionIdsJson = JsonSerializer.Serialize(list); } private void ParseAndSetAnimationsFromForm() { var ids = Request.Form["npc_anim_id[]"].ToArray(); var overrides = Request.Form["npc_anim_override_key[]"].ToArray(); var enabledValues = Request.Form["npc_anim_enabled[]"].ToHashSet(StringComparer.OrdinalIgnoreCase); var selected = new List(); for (var i = 0; i < ids.Length; i++) { if (!int.TryParse(ids[i], out var animId) || animId <= 0) continue; var isEnabled = enabledValues.Contains(i.ToString()); var ov = i < overrides.Length ? overrides[i]?.Trim() : null; if (string.IsNullOrWhiteSpace(ov)) ov = null; selected.Add(new NpcAnimationSelection { AnimationDefinitionId = animId, OverrideKey = ov, IsEnabled = isEnabled }); } selected = selected .GroupBy(x => new { x.AnimationDefinitionId, Key = (x.OverrideKey ?? "").Trim().ToLowerInvariant() }) .Select(g => g.First()) .ToList(); SelectedAnimations = selected; var enabled = selected.Where(s => s.IsEnabled).ToList(); if (enabled.Count == 0) { Npc.SpriteConfigJson = null; return; } var byId = AllAnimations.Where(a => a.SpriteSheet != null).ToDictionary(a => a.Id, a => a); var sheets = new Dictionary(); var sheetKeyById = new Dictionary(); var animations = new Dictionary(); foreach (var sel in enabled) { if (!byId.TryGetValue(sel.AnimationDefinitionId, out var anim)) continue; var sheet = anim.SpriteSheet; if (sheet == null) continue; if (!sheetKeyById.TryGetValue(sheet.Id, out var sheetKey)) { sheetKey = $"sheet_{sheet.Id}"; sheetKeyById[sheet.Id] = sheetKey; sheets[sheetKey] = new { path = sheet.CdnPath, width = sheet.SheetWidth, height = sheet.SheetHeight, frameWidth = sheet.FrameWidth, frameHeight = sheet.FrameHeight }; } var key = !string.IsNullOrWhiteSpace(sel.OverrideKey) ? sel.OverrideKey! : anim.Key; animations[key] = new { sheet = sheetKey, frames = ParseFrameSequence(anim.FrameSequence), fps = anim.Fps, loop = anim.Loop, flipX = anim.FlipX, flipY = anim.FlipY }; } if (animations.Count == 0) { Npc.SpriteConfigJson = null; return; } Npc.SpriteConfigJson = JsonSerializer.Serialize(new { sheets, animations }); } private static int[] ParseFrameSequence(string frameSequence) { if (string.IsNullOrWhiteSpace(frameSequence)) return new[] { 0 }; return frameSequence .Split(',') .Select(s => int.TryParse(s.Trim(), out var n) ? n : 0) .ToArray(); } }