using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using GameServer.Dungeon; using DataServer.Data; using DataServer.Data.Entities; using System.Text.Json; namespace GameServices.Admin.Pages.Dungeons; public class ViewModel : AdminPageModel { private readonly DungeonHandler _dungeonHandler; private readonly GameDbContext _db; public ViewModel(DungeonHandler dungeonHandler, GameDbContext db) { _dungeonHandler = dungeonHandler; _db = db; } public GameServer.Dungeon.DungeonInstance? Dungeon { get; set; } public string Duration { get; set; } = ""; public int MapWidth { get; set; } public int MapHeight { get; set; } public string WalkableJson { get; set; } = "[]"; public string PlayersJson { get; set; } = "[]"; public string MobsJson { get; set; } = "[]"; public string VisualTilesJson { get; set; } = "[]"; public string TileSheetsJson { get; set; } = "[]"; public int VisualTileCount { get; set; } public List MobDefinitions { get; set; } = new(); public List AbilityDefinitions { get; set; } = new(); public List ResistanceTypes { get; set; } = new(); public async Task OnGetAsync(Guid id) { Dungeon = _dungeonHandler.GetDungeon(id); MobDefinitions = await _db.DungeonMobDefinitions .Where(m => m.IsEnabled).OrderBy(m => m.Name).ToListAsync(); AbilityDefinitions = await _db.MobAbilityDefinitions .Where(a => a.IsEnabled).OrderBy(a => a.Name).ToListAsync(); ResistanceTypes = await _db.DamageResistanceTypes .Where(r => r.IsEnabled) .OrderBy(r => r.SortOrder) .ThenBy(r => r.DisplayName) .ToListAsync(); // Load ALL available tile sheets from database (not just those in dungeon) var allSheets = await _db.Set() .Where(s => s.IsEnabled) .OrderBy(s => s.Name) .ToListAsync(); TileSheetsJson = JsonSerializer.Serialize(allSheets.Select(s => new { id = s.Id, name = s.Name, path = s.CdnPath, tileW = s.TileWidth, tileH = s.TileHeight, sheetW = s.SheetWidth, sheetH = s.SheetHeight, cols = s.Columns })); if (Dungeon == null) return; Duration = FormatDuration(DateTime.UtcNow - Dungeon.CreatedAt); var layout = Dungeon.LayoutV2; if (layout != null) { MapWidth = layout.Width; MapHeight = layout.Height; var walkable = new List(); for (int y = 0; y < layout.Height; y++) for (int x = 0; x < layout.Width; x++) walkable.Add(layout.Walkable[x, y]); WalkableJson = JsonSerializer.Serialize(walkable); VisualTileCount = layout.TileDetails.Count; VisualTilesJson = JsonSerializer.Serialize(layout.TileDetails.Select(t => new { x = t.X, y = t.Y, sid = t.SheetId, frame = t.FrameIndex, l = t.Layer, r = t.Rotation, fx = t.FlipX, fy = t.FlipY })); } else { MapWidth = 100; MapHeight = 100; } PlayersJson = JsonSerializer.Serialize(Dungeon.Simulation.Players.Values.Select(p => new { id = p.CharacterId.ToString(), name = p.CharacterName, x = p.X, y = p.Y, health = p.Health, maxHealth = p.MaxHealth, isAlive = p.IsAlive })); MobsJson = JsonSerializer.Serialize(Dungeon.Simulation.Mobs.Values.Select(m => new { id = m.Id, name = m.Name, x = m.X, y = m.Y, health = m.Health, maxHealth = m.MaxHealth, alive = m.IsAlive, isBoss = m.Type == DataServer.Data.Enums.MobType.Boss, state = m.State.ToString(), abilities = m.Abilities.Select(a => new { id = a.AbilityId, name = a.Definition?.Name ?? $"Ability {a.AbilityId}", key = a.Definition?.Key ?? "" }), resistances = m.Stats.Resistances, lootGold = m.DeathLootGold, lootItems = m.DeathLoot == null ? Array.Empty() : m.DeathLoot.Select(l => new { id = l.ItemDefinitionId, name = l.Item?.Name ?? $"Item {l.ItemDefinitionId}", qty = l.Quantity }) })); } public IActionResult OnGetStatus(Guid id) { var dungeon = _dungeonHandler.GetDungeon(id); if (dungeon == null) return new JsonResult(new { error = "Not found" }) { StatusCode = 404 }; return new JsonResult(new { playerCount = dungeon.Simulation.Players.Count, mobsAlive = dungeon.Simulation.Mobs.Values.Count(m => m.IsAlive), duration = FormatDuration(DateTime.UtcNow - dungeon.CreatedAt), players = dungeon.Simulation.Players.Values.Select(p => new { id = p.CharacterId.ToString(), name = p.CharacterName, x = p.X, y = p.Y, health = p.Health, maxHealth = p.MaxHealth }), mobs = dungeon.Simulation.Mobs.Values.Select(m => new { id = m.Id, name = m.Name, x = m.X, y = m.Y, health = m.Health, maxHealth = m.MaxHealth, alive = m.IsAlive, isBoss = m.Type == DataServer.Data.Enums.MobType.Boss, state = m.State.ToString(), abilities = m.Abilities.Select(a => new { id = a.AbilityId, name = a.Definition?.Name ?? $"Ability {a.AbilityId}", key = a.Definition?.Key ?? "" }), resistances = m.Stats.Resistances, lootGold = m.DeathLootGold, lootItems = m.DeathLoot == null ? Array.Empty() : m.DeathLoot.Select(l => new { id = l.ItemDefinitionId, name = l.Item?.Name ?? $"Item {l.ItemDefinitionId}", qty = l.Quantity }) }) }); } public IActionResult OnPostSetTile(Guid id, int x, int y, bool walkable) { return new JsonResult(new { success = _dungeonHandler.SetTileWalkable(id, x, y, walkable) }); } public IActionResult OnPostPlaceVisualTile(Guid id, int x, int y, int sheetId, int frameIndex, int layer = 0, bool walkable = true) { return new JsonResult(new { success = _dungeonHandler.PlaceVisualTile(id, x, y, sheetId, frameIndex, layer, walkable) }); } public IActionResult OnPostRemoveTile(Guid id, int x, int y, int? layer = null) { return new JsonResult(new { success = _dungeonHandler.RemoveTile(id, x, y, layer) }); } public IActionResult OnPostFillRect(Guid id, int x1, int y1, int x2, int y2, bool walkable) { return new JsonResult(new { success = _dungeonHandler.FillTileRect(id, x1, y1, x2, y2, walkable) > 0 }); } public IActionResult OnPostBroadcastTiles(Guid id) { var dungeon = _dungeonHandler.GetDungeon(id); if (dungeon == null) return new JsonResult(new { error = "Not found" }) { StatusCode = 404 }; dungeon.HasPendingTileUpdates = true; return new JsonResult(new { success = true }); } public IActionResult OnPostKillMob(Guid id, int mobId) { var dungeon = _dungeonHandler.GetDungeon(id); if (dungeon?.Simulation.Mobs.TryGetValue(mobId, out var mob) == true) { mob.Health = 0; mob.IsAlive = false; return new JsonResult(new { success = true }); } return new JsonResult(new { error = "Not found" }) { StatusCode = 404 }; } public IActionResult OnPostHealMob(Guid id, int mobId) { var dungeon = _dungeonHandler.GetDungeon(id); if (dungeon?.Simulation.Mobs.TryGetValue(mobId, out var mob) == true) { mob.Health = mob.MaxHealth; mob.IsAlive = true; return new JsonResult(new { success = true }); } return new JsonResult(new { error = "Not found" }) { StatusCode = 404 }; } public async Task OnPostAddMobAbilityAsync(Guid id, int mobId, int abilityId) { var dungeon = _dungeonHandler.GetDungeon(id); if (dungeon?.Simulation.Mobs.TryGetValue(mobId, out var mob) != true) return new JsonResult(new { error = "Mob not found" }) { StatusCode = 404 }; var ability = await _db.MobAbilityDefinitions.FirstOrDefaultAsync(a => a.Id == abilityId && a.IsEnabled); if (ability == null) return new JsonResult(new { error = "Ability not found" }) { StatusCode = 404 }; if (mob.Abilities.Any(a => a.AbilityId == abilityId)) return new JsonResult(new { success = true, message = "Ability already present" }); mob.Abilities.Add(new MobAbilityState { AbilityId = ability.Id, Definition = ability, CooldownRemaining = 0, Priority = ability.Priority }); return new JsonResult(new { success = true }); } public IActionResult OnPostSetMobResistance(Guid id, int mobId, string key, float value, bool remove = false) { var dungeon = _dungeonHandler.GetDungeon(id); if (dungeon?.Simulation.Mobs.TryGetValue(mobId, out var mob) != true) return new JsonResult(new { error = "Mob not found" }) { StatusCode = 404 }; if (remove) mob.Stats.Resistances.Remove(key); else mob.Stats.Resistances[key] = value; return new JsonResult(new { success = true }); } public IActionResult OnPostSetMobLootGold(Guid id, int mobId, long gold) { var dungeon = _dungeonHandler.GetDungeon(id); if (dungeon?.Simulation.Mobs.TryGetValue(mobId, out var mob) != true) return new JsonResult(new { error = "Mob not found" }) { StatusCode = 404 }; mob.DeathLootGold = Math.Max(0, gold); return new JsonResult(new { success = true }); } public async Task OnPostAddMobLootItemAsync(Guid id, int mobId, int itemId, int quantity) { if (quantity <= 0) return new JsonResult(new { error = "Quantity must be > 0" }) { StatusCode = 400 }; var dungeon = _dungeonHandler.GetDungeon(id); if (dungeon?.Simulation.Mobs.TryGetValue(mobId, out var mob) != true) return new JsonResult(new { error = "Mob not found" }) { StatusCode = 404 }; var item = await _db.Set().FirstOrDefaultAsync(i => i.Id == itemId); if (item == null) return new JsonResult(new { error = "Item not found" }) { StatusCode = 404 }; mob.DeathLoot ??= new List(); var existing = mob.DeathLoot.FirstOrDefault(l => l.ItemDefinitionId == itemId); if (existing != null) existing.Quantity += quantity; else mob.DeathLoot.Add(new LootDrop { ItemDefinitionId = itemId, Item = item, Quantity = quantity }); return new JsonResult(new { success = true }); } public IActionResult OnPostSpawnMob(Guid id, int mobDefId, float x, float y) { var mob = _dungeonHandler.SpawnMobInDungeon(id, mobDefId, x, y); return mob != null ? new JsonResult(new { success = true, mobId = mob.Id }) : new JsonResult(new { error = "Failed" }) { StatusCode = 400 }; } public IActionResult OnPostKillAllMobs(Guid id) { var dungeon = _dungeonHandler.GetDungeon(id); if (dungeon != null) foreach (var mob in dungeon.Simulation.Mobs.Values) { mob.Health = 0; mob.IsAlive = false; } return RedirectToPage(new { id }); } public IActionResult OnPostHealPlayer(Guid id, string playerId) { if (!ulong.TryParse(playerId, out var charId)) return new JsonResult(new { error = "Invalid ID" }) { StatusCode = 400 }; return new JsonResult(new { success = _dungeonHandler.HealPlayer(id, charId) }); } public IActionResult OnPostTeleportPlayer(Guid id, string playerId, float x, float y) { if (!ulong.TryParse(playerId, out var charId)) return new JsonResult(new { error = "Invalid ID" }) { StatusCode = 400 }; return new JsonResult(new { success = _dungeonHandler.TeleportPlayer(id, charId, x, y) }); } public IActionResult OnPostKillPlayer(Guid id, string playerId) { if (!ulong.TryParse(playerId, out var charId)) return new JsonResult(new { error = "Invalid ID" }) { StatusCode = 400 }; return new JsonResult(new { success = _dungeonHandler.KillPlayer(id, charId) }); } public IActionResult OnPostSetGodMode(Guid id, string playerId, bool enabled) { if (!ulong.TryParse(playerId, out var charId)) return new JsonResult(new { error = "Invalid ID" }) { StatusCode = 400 }; return new JsonResult(new { success = _dungeonHandler.SetPlayerInvulnerable(id, charId, enabled) }); } public IActionResult OnPostCompleteDungeon(Guid id) { var dungeon = _dungeonHandler.GetDungeon(id); dungeon?.Simulation.ForceComplete(); return RedirectToPage(new { id }); } private static string FormatDuration(TimeSpan d) => d.TotalHours >= 1 ? $"{(int)d.TotalHours}h {d.Minutes}m" : d.TotalMinutes >= 1 ? $"{(int)d.TotalMinutes}m {d.Seconds}s" : $"{(int)d.TotalSeconds}s"; }