using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using DataServer.Data; using DataServer.Data.Entities; using Server.Networking; using GameServer.Networking.DTOs; using Server.Networking.Messages; namespace GameServer.Dungeon; public sealed partial class DungeonHandler { #region Loot Chest Handlers /// /// Handle opening a loot chest /// private async Task HandleLootChestOpen(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) { var json = System.Text.Encoding.UTF8.GetString(payload.Span); var request = System.Text.Json.JsonSerializer.Deserialize(json); if (request == null) return; if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return; if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest)) { await SendErrorAsync(connection, "Chest not found", ct); return; } // Check ownership if (chest.OwnerCharacterId != session.CharacterId) { await SendErrorAsync(connection, "This chest doesn't belong to you", ct); return; } // Check distance if (session.PlayerInstance != null) { float dist = MathF.Sqrt( MathF.Pow(session.PlayerInstance.X - chest.X, 2) + MathF.Pow(session.PlayerInstance.Y - chest.Y, 2)); if (dist > 96) // Interaction range { await SendErrorAsync(connection, "Too far from chest", ct); return; } } chest.IsOpen = true; // Load item definitions for display using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var itemDefIds = chest.Items.Select(i => i.ItemDefinitionId).Distinct().ToList(); var itemDefs = await db.Set() .Where(d => itemDefIds.Contains(d.Id)) .ToDictionaryAsync(d => d.Id, ct); // Build chest state var chestItems = new object?[100]; foreach (var item in chest.Items) { if (itemDefs.TryGetValue(item.ItemDefinitionId, out var def)) { chestItems[item.SlotIndex] = new { slotIndex = item.SlotIndex, definitionId = def.Id, name = def.Name, description = def.Description, type = def.Type.ToString(), rarity = def.Rarity.ToString(), quantity = item.Quantity, spritePath = def.SpritePath, tintColor = def.TintColor }; } } await SendAsync(connection, DungeonOpCodes.LOOT_CHEST_STATE, new { chestId = chest.Id, gold = chest.Gold, items = chestItems, slots = 100 }, ct); } /// /// Handle taking a single item from loot chest /// private async Task HandleLootChestTakeItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) { var json = System.Text.Encoding.UTF8.GetString(payload.Span); var request = System.Text.Json.JsonSerializer.Deserialize(json); if (request == null) return; if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return; if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest)) return; if (chest.OwnerCharacterId != session.CharacterId) return; // Find the item in chest var chestItem = chest.Items.FirstOrDefault(i => i.SlotIndex == request.SlotIndex); if (chestItem == null) { await SendErrorAsync(connection, "Item not found in chest", ct); return; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // Get item definition var itemDef = await db.Set() .FirstOrDefaultAsync(d => d.Id == chestItem.ItemDefinitionId, ct); if (itemDef == null) return; // Get player's current inventory var existingItems = await db.Set() .Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped) .ToListAsync(ct); // Find an available slot var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet(); int targetSlot = request.TargetSlotIndex; if (targetSlot < 0 || targetSlot >= 30 || usedSlots.Contains(targetSlot)) { // Find first available slot targetSlot = -1; for (int i = 0; i < 30; i++) { if (!usedSlots.Contains(i)) { targetSlot = i; break; } } } if (targetSlot < 0) { await SendErrorAsync(connection, "Inventory full", ct); return; } // Add to player inventory var newItem = new DungeonCharacterItem { CharacterId = session.CharacterId, ItemDefinitionId = chestItem.ItemDefinitionId, Quantity = chestItem.Quantity, SlotIndex = targetSlot }; db.Set().Add(newItem); // Update database chest item as taken var dbChestItem = await db.DeathChestItems .FirstOrDefaultAsync(i => i.DeathChestId == chest.DatabaseId && i.SlotIndex == request.SlotIndex && !i.IsTaken, ct); if (dbChestItem != null) { dbChestItem.IsTaken = true; dbChestItem.TakenAt = DateTime.UtcNow; } await db.SaveChangesAsync(ct); // Remove from runtime chest chest.Items.Remove(chestItem); // Check if chest is now empty await CheckAndRemoveEmptyChestAsync(db, dungeon, chest, session, ct); // Send updated states await HandleInventoryRequest(connection, session, ct); // Only resend chest state if it still exists if (!chest.IsEmpty) { await HandleLootChestOpen(connection, session, payload, ct); } } /// /// Handle taking all items from loot chest /// private async Task HandleLootChestTakeAll(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) { var json = System.Text.Encoding.UTF8.GetString(payload.Span); var request = System.Text.Json.JsonSerializer.Deserialize(json); if (request == null) return; if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return; if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest)) return; if (chest.OwnerCharacterId != session.CharacterId) return; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // Get player's current inventory var existingItems = await db.Set() .Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped) .ToListAsync(ct); var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet(); var itemsTaken = new List(); var takenLoot = new List(); // Try to take each item foreach (var chestItem in chest.Items.ToList()) { // Find available slot int targetSlot = -1; for (int i = 0; i < 30; i++) { if (!usedSlots.Contains(i)) { targetSlot = i; usedSlots.Add(i); break; } } if (targetSlot < 0) break; // Inventory full // Get item definition for popup var itemDef = await db.Set() .FirstOrDefaultAsync(d => d.Id == chestItem.ItemDefinitionId, ct); // Add to player inventory var newItem = new DungeonCharacterItem { CharacterId = session.CharacterId, ItemDefinitionId = chestItem.ItemDefinitionId, Quantity = chestItem.Quantity, SlotIndex = targetSlot }; db.Set().Add(newItem); // Update database chest item as taken var dbChestItem = await db.DeathChestItems .FirstOrDefaultAsync(i => i.DeathChestId == chest.DatabaseId && i.SlotIndex == chestItem.SlotIndex && !i.IsTaken, ct); if (dbChestItem != null) { dbChestItem.IsTaken = true; dbChestItem.TakenAt = DateTime.UtcNow; } itemsTaken.Add(chestItem); if (itemDef != null) { takenLoot.Add(new LootDrop { ItemDefinitionId = chestItem.ItemDefinitionId, Item = itemDef, Quantity = chestItem.Quantity }); } } // Take gold if (chest.Gold > 0) { var character = await db.DungeonCharacters.FindAsync(new object[] { session.CharacterId }, ct); if (character != null) { character.Gold += chest.Gold; // Update database chest var dbChest = await db.DeathChests.FindAsync(new object[] { chest.DatabaseId }, ct); if (dbChest != null) { dbChest.GoldAmount = 0; } chest.Gold = 0; } } await db.SaveChangesAsync(ct); // Remove taken items from runtime chest foreach (var item in itemsTaken) { chest.Items.Remove(item); } // Send loot popup if (takenLoot.Count > 0) { await SendLootPopupAsync(session, takenLoot); } // Check if chest is now empty await CheckAndRemoveEmptyChestAsync(db, dungeon, chest, session, ct); // Send updated inventory await HandleInventoryRequest(connection, session, ct); // If chest still has items, send updated state if (!chest.IsEmpty) { var openPayload = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes( new LootChestOpenRequest { ChestId = request.ChestId }); await HandleLootChestOpen(connection, session, openPayload, ct); } } /// /// Handle closing a loot chest /// private async Task HandleLootChestClose(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) { var json = System.Text.Encoding.UTF8.GetString(payload.Span); var request = System.Text.Json.JsonSerializer.Deserialize(json); if (request == null) return; if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return; if (dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest)) { if (chest.OwnerCharacterId == session.CharacterId) { chest.IsOpen = false; } } } /// /// Check if a chest is empty and remove it if so /// private async Task CheckAndRemoveEmptyChestAsync(GameDbContext db, DungeonInstance dungeon, LootChestInstance chest, DungeonPlayerSession owner, CancellationToken ct) { if (chest.IsEmpty) { // Update database var dbChest = await db.DeathChests.FindAsync(new object[] { chest.DatabaseId }, ct); if (dbChest != null) { dbChest.IsEmpty = true; dbChest.EmptiedAt = DateTime.UtcNow; await db.SaveChangesAsync(ct); } // Notify owner that chest is removed await SendAsync(owner.Connection, DungeonOpCodes.LOOT_CHEST_REMOVED, new { chestId = chest.Id }, ct); // Remove from runtime dungeon.Simulation.LootChests.TryRemove(chest.Id, out _); _log.LogInformation("Loot chest {ChestId} emptied and removed", chest.Id); } } #endregion }