using System.Globalization; using System.Text; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class MapRegionAssetImportSummary { public int MapGroupCount { get; init; } public int RegionCount { get; init; } public int DistinctMapCount { get; init; } public int MissingAssetMapCount { get; init; } public int CurrentMapRegionListCount { get; init; } public int CurrentMapRegionCount { get; init; } public int UpdatedMapRegionListCount { get; init; } public int InsertedMapRegionListCount { get; init; } public int DeletedMapRegionCount { get; init; } public int InsertedMapRegionCount { get; init; } public int BuffRegionCount { get; init; } public int LimitEvoRegionCount { get; init; } } public static class MapRegionAssetImporter { public static MapRegionAssetImportSummary ValidateXml(string mapRegionXmlPath, string mapBuffRegionXmlPath, string mapLimitEvoXmlPath) { List groups = LoadMapRegionGroups(mapRegionXmlPath); return new MapRegionAssetImportSummary { MapGroupCount = groups.Count, RegionCount = groups.Sum(x => x.Regions.Count), DistinctMapCount = groups.Select(x => x.MapId).Distinct().Count(), BuffRegionCount = CountElements(mapBuffRegionXmlPath, "BuffRegion"), LimitEvoRegionCount = CountElements(mapLimitEvoXmlPath, "LimitEvoRegion") }; } public static MapRegionAssetImportSummary AssessDatabase(string connectionString, string mapRegionXmlPath, string mapBuffRegionXmlPath, string mapLimitEvoXmlPath) { List groups = LoadMapRegionGroups(mapRegionXmlPath); using SqlConnection connection = new(connectionString); connection.Open(); HashSet assetMapIds = ReadIntSet(connection, "SELECT [MapId] FROM [Asset].[Map];"); return new MapRegionAssetImportSummary { MapGroupCount = groups.Count, RegionCount = groups.Sum(x => x.Regions.Count), DistinctMapCount = groups.Select(x => x.MapId).Distinct().Count(), MissingAssetMapCount = groups.Select(x => x.MapId).Distinct().Count(x => !assetMapIds.Contains(x)), CurrentMapRegionListCount = ExecuteScalarInt(connection, "SELECT COUNT(*) FROM [Asset].[MapRegionList];"), CurrentMapRegionCount = ExecuteScalarInt(connection, "SELECT COUNT(*) FROM [Asset].[MapRegion];"), BuffRegionCount = CountElements(mapBuffRegionXmlPath, "BuffRegion"), LimitEvoRegionCount = CountElements(mapLimitEvoXmlPath, "LimitEvoRegion") }; } public static MapRegionAssetImportSummary ImportMergeReplace(string connectionString, string mapRegionXmlPath, string mapBuffRegionXmlPath, string mapLimitEvoXmlPath) { List groups = LoadMapRegionGroups(mapRegionXmlPath); using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { Dictionary mapNames = ReadMapNames(connection, transaction); int missingAssetMapCount = groups.Select(x => x.MapId).Distinct().Count(x => !mapNames.ContainsKey(x)); if (missingAssetMapCount > 0) { throw new InvalidOperationException($"MapRegion.xml contains {missingAssetMapCount} map ids that do not exist in Asset.Map. Import MapList first or fix the missing maps before importing MapRegion."); } EnsureNoDuplicateMapRegionLists(connection, transaction); int currentMapRegionListCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[MapRegionList];"); int currentMapRegionCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[MapRegion];"); int updatedMapRegionListCount = 0; int insertedMapRegionListCount = 0; int deletedMapRegionCount = 0; int insertedMapRegionCount = 0; foreach (MapRegionGroupRecord group in groups) { long? existingListId = TryGetMapRegionListId(connection, transaction, group.MapId); long listId; string mapName = mapNames[group.MapId]; if (existingListId.HasValue) { listId = existingListId.Value; ExecuteNonQuery( connection, transaction, "UPDATE [Asset].[MapRegionList] SET [Name] = @Name WHERE [Id] = @Id;", new SqlParameter("@Name", System.Data.SqlDbType.VarChar, 200) { Value = mapName }, new SqlParameter("@Id", System.Data.SqlDbType.BigInt) { Value = listId }); updatedMapRegionListCount++; } else { listId = InsertMapRegionList(connection, transaction, group.MapId, mapName); insertedMapRegionListCount++; } deletedMapRegionCount += ExecuteNonQuery( connection, transaction, "DELETE FROM [Asset].[MapRegion] WHERE [MapRegionListId] = @MapRegionListId;", new SqlParameter("@MapRegionListId", System.Data.SqlDbType.BigInt) { Value = listId }); insertedMapRegionCount += InsertRegions(connection, transaction, listId, group.Regions); } transaction.Commit(); return new MapRegionAssetImportSummary { MapGroupCount = groups.Count, RegionCount = groups.Sum(x => x.Regions.Count), DistinctMapCount = groups.Select(x => x.MapId).Distinct().Count(), MissingAssetMapCount = missingAssetMapCount, CurrentMapRegionListCount = currentMapRegionListCount, CurrentMapRegionCount = currentMapRegionCount, UpdatedMapRegionListCount = updatedMapRegionListCount, InsertedMapRegionListCount = insertedMapRegionListCount, DeletedMapRegionCount = deletedMapRegionCount, InsertedMapRegionCount = insertedMapRegionCount, BuffRegionCount = CountElements(mapBuffRegionXmlPath, "BuffRegion"), LimitEvoRegionCount = CountElements(mapLimitEvoXmlPath, "LimitEvoRegion") }; } catch { transaction.Rollback(); throw; } } private static List LoadMapRegionGroups(string xmlPath) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("MapRegion.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "MapRegionTable") { throw new InvalidOperationException("MapRegion.xml root node must be ."); } List groups = new(); int groupIndex = 0; HashSet mapIds = new(); foreach (XElement groupElement in root.Elements("MapRegionGroup")) { groupIndex++; string groupContext = $"MapRegion group {groupIndex}"; int declaredRegionCount = ReadRequiredInt(groupElement, "RegionCount", groupContext); List regionElements = groupElement.Elements("Region").ToList(); if (regionElements.Count != declaredRegionCount) { throw new InvalidOperationException($"{groupContext} declares RegionCount={declaredRegionCount}, but contains {regionElements.Count} rows."); } if (regionElements.Count == 0) { throw new InvalidOperationException($"{groupContext} does not contain any region rows."); } int mapId = ReadRequiredInt(regionElements[0], "s_dwMapID", $"{groupContext} row 1"); if (!mapIds.Add(mapId)) { throw new InvalidOperationException($"MapRegion.xml contains duplicate MapRegionGroup entries for MapId {mapId}."); } List regions = new(); for (int regionIndex = 0; regionIndex < regionElements.Count; regionIndex++) { XElement regionElement = regionElements[regionIndex]; string rowContext = $"{groupContext} row {regionIndex + 1}"; int rowMapId = ReadRequiredInt(regionElement, "s_dwMapID", rowContext); if (rowMapId != mapId) { throw new InvalidOperationException($"{rowContext} has MapId {rowMapId}, but its group started with MapId {mapId}."); } if (regionIndex > byte.MaxValue) { throw new InvalidOperationException($"{rowContext} has region index {regionIndex}, which exceeds tinyint max value 255."); } string name = CleanName(ReadRequiredString(regionElement, "s_szDiscript", rowContext)); if (string.IsNullOrWhiteSpace(name)) { name = $"Map {mapId} Region {regionIndex}"; } if (name.Length > 200) { name = name[..200]; } regions.Add(new MapRegionRecord { Index = (byte)regionIndex, X = ReadRequiredInt(regionElement, "s_nCenterX", rowContext), Y = ReadRequiredInt(regionElement, "s_nCenterY", rowContext), Name = name }); } groups.Add(new MapRegionGroupRecord { MapId = mapId, Regions = regions }); } if (groups.Count == 0) { throw new InvalidOperationException("MapRegion.xml does not contain any rows."); } return groups; } private static int InsertRegions(SqlConnection connection, SqlTransaction transaction, long mapRegionListId, IReadOnlyList regions) { using SqlCommand command = new(@" INSERT INTO [Asset].[MapRegion] ([Index], [X], [Y], [Name], [MapRegionListId]) VALUES (@Index, @X, @Y, @Name, @MapRegionListId);", connection, transaction); command.Parameters.Add("@Index", System.Data.SqlDbType.TinyInt); command.Parameters.Add("@X", System.Data.SqlDbType.Int); command.Parameters.Add("@Y", System.Data.SqlDbType.Int); command.Parameters.Add("@Name", System.Data.SqlDbType.VarChar, 200); command.Parameters.Add("@MapRegionListId", System.Data.SqlDbType.BigInt); int inserted = 0; foreach (MapRegionRecord region in regions) { command.Parameters["@Index"].Value = region.Index; command.Parameters["@X"].Value = region.X; command.Parameters["@Y"].Value = region.Y; command.Parameters["@Name"].Value = region.Name; command.Parameters["@MapRegionListId"].Value = mapRegionListId; inserted += command.ExecuteNonQuery(); } return inserted; } private static long InsertMapRegionList(SqlConnection connection, SqlTransaction transaction, int mapId, string name) { using SqlCommand command = new(@" INSERT INTO [Asset].[MapRegionList] ([MapId], [Name]) OUTPUT INSERTED.[Id] VALUES (@MapId, @Name);", connection, transaction); command.Parameters.Add("@MapId", System.Data.SqlDbType.Int).Value = mapId; command.Parameters.Add("@Name", System.Data.SqlDbType.VarChar, 200).Value = name; object? value = command.ExecuteScalar(); return Convert.ToInt64(value, CultureInfo.InvariantCulture); } private static long? TryGetMapRegionListId(SqlConnection connection, SqlTransaction transaction, int mapId) { using SqlCommand command = new("SELECT [Id] FROM [Asset].[MapRegionList] WHERE [MapId] = @MapId;", connection, transaction); command.Parameters.Add("@MapId", System.Data.SqlDbType.Int).Value = mapId; object? value = command.ExecuteScalar(); return value == null ? null : Convert.ToInt64(value, CultureInfo.InvariantCulture); } private static Dictionary ReadMapNames(SqlConnection connection, SqlTransaction transaction) { using SqlCommand command = new("SELECT [MapId], [Name] FROM [Asset].[Map];", connection, transaction); using SqlDataReader reader = command.ExecuteReader(); Dictionary mapNames = new(); while (reader.Read()) { string name = Convert.ToString(reader.GetValue(1), CultureInfo.InvariantCulture) ?? string.Empty; mapNames[reader.GetInt32(0)] = name.Length > 200 ? name[..200] : name; } return mapNames; } private static void EnsureNoDuplicateMapRegionLists(SqlConnection connection, SqlTransaction transaction) { int duplicateCount = ExecuteScalarInt( connection, transaction, "SELECT COUNT(*) FROM (SELECT [MapId] FROM [Asset].[MapRegionList] GROUP BY [MapId] HAVING COUNT(*) > 1) AS DuplicateMapIds;"); if (duplicateCount > 0) { throw new InvalidOperationException($"Asset.MapRegionList contains {duplicateCount} duplicate MapId entries. Clean those duplicates before importing MapRegion."); } } private static string CleanName(string value) { int helperIndex = value.IndexOf("= 0) { value = value[..helperIndex]; } StringBuilder builder = new(); foreach (char character in value) { if (character is >= ' ' and <= '~') { builder.Append(character); continue; } break; } return string.Join(' ', builder.ToString().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)).Trim(); } private static int CountElements(string xmlPath, string elementName) { if (!File.Exists(xmlPath)) { return 0; } XDocument document = XDocument.Load(xmlPath); return document.Descendants(elementName).Count(); } private static int ReadRequiredInt(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } if (!int.TryParse(element.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) { throw new InvalidOperationException($"{recordContext} has invalid integer value in '{elementName}': '{element.Value}'."); } return value; } private static string ReadRequiredString(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } return element.Value; } private static HashSet ReadIntSet(SqlConnection connection, string sql) { using SqlCommand command = new(sql, connection); using SqlDataReader reader = command.ExecuteReader(); HashSet values = new(); while (reader.Read()) { values.Add(Convert.ToInt32(reader.GetValue(0), CultureInfo.InvariantCulture)); } return values; } private static int ExecuteScalarInt(SqlConnection connection, string sql) { using SqlCommand command = new(sql, connection); object? value = command.ExecuteScalar(); return Convert.ToInt32(value, CultureInfo.InvariantCulture); } private static int ExecuteScalarInt(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); object? value = command.ExecuteScalar(); return Convert.ToInt32(value, CultureInfo.InvariantCulture); } private static int ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, string sql, params SqlParameter[] parameters) { using SqlCommand command = new(sql, connection, transaction); command.Parameters.AddRange(parameters); return command.ExecuteNonQuery(); } private sealed class MapRegionGroupRecord { public int MapId { get; init; } public List Regions { get; init; } = new(); } private sealed class MapRegionRecord { public byte Index { get; init; } public int X { get; init; } public int Y { get; init; } public string Name { get; init; } = string.Empty; } } }