using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class DigimonBookImportSummary { public int BookInfoXmlRecordCount { get; init; } public int SyntheticBookInfoCount { get; init; } public int DeckBuffRecordCount { get; init; } public int DeckBuffOptionRecordCount { get; init; } public int EncyclopediaExceptionRecordCount { get; init; } public int DeckCompositionRecordCount { get; init; } public int DeletedDeckBookInfoCount { get; init; } public int DeletedDeckBuffCount { get; init; } public int DeletedDeckBuffOptionCount { get; init; } public int InsertedDeckBookInfoCount { get; init; } public int InsertedDeckBuffCount { get; init; } public int InsertedDeckBuffOptionCount { get; init; } } public static class DigimonBookAssetImporter { public static DigimonBookImportSummary ValidateXml( string bookInfoXmlPath, string deckOptionXmlPath, string encyclopediaExceptionXmlPath, string deckCompositionXmlPath) { DigimonBookImportPackage package = LoadPackage( bookInfoXmlPath, deckOptionXmlPath, encyclopediaExceptionXmlPath, deckCompositionXmlPath); return BuildSummary(package); } public static DigimonBookImportSummary ImportReplace( string connectionString, string bookInfoXmlPath, string deckOptionXmlPath, string encyclopediaExceptionXmlPath, string deckCompositionXmlPath) { DigimonBookImportPackage package = LoadPackage( bookInfoXmlPath, deckOptionXmlPath, encyclopediaExceptionXmlPath, deckCompositionXmlPath); if (package.BookInfos.Count == 0 || package.DeckBuffs.Count == 0) { throw new InvalidOperationException("Digimon_Book XML does not contain the required BookInfo or DeckOption records."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { int deletedDeckBuffOptionCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[DeckBuffOption];"); int deletedDeckBuffCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[DeckBuff];"); int deletedDeckBookInfoCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[DeckBookInfo];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[DeckBuffOption];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[DeckBuff];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[DeckBookInfo];"); ExecuteNonQuery(connection, transaction, "DBCC CHECKIDENT(N'[Asset].[DeckBuffOption]', RESEED, 0);"); ExecuteNonQuery(connection, transaction, "DBCC CHECKIDENT(N'[Asset].[DeckBuff]', RESEED, 0);"); ExecuteNonQuery(connection, transaction, "DBCC CHECKIDENT(N'[Asset].[DeckBookInfo]', RESEED, 0);"); using (SqlCommand bookInfoCommand = new(@" INSERT INTO [Asset].[DeckBookInfo] ([OptionId], [Type], [Name], [Explain]) VALUES (@OptionId, @Type, @Name, @Explain);", connection, transaction)) { AddParameter(bookInfoCommand, "@OptionId"); AddParameter(bookInfoCommand, "@Type"); AddParameter(bookInfoCommand, "@Name"); AddParameter(bookInfoCommand, "@Explain"); foreach (DeckBookInfoRecord record in package.BookInfos) { bookInfoCommand.Parameters["@OptionId"].Value = record.OptionId; bookInfoCommand.Parameters["@Type"].Value = record.Type; bookInfoCommand.Parameters["@Name"].Value = record.Name; bookInfoCommand.Parameters["@Explain"].Value = record.Explain; bookInfoCommand.ExecuteNonQuery(); } } using (SqlCommand deckBuffCommand = new(@" INSERT INTO [Asset].[DeckBuff] ([GroupIdX], [GroupName], [Explain]) VALUES (@GroupIdX, @GroupName, @Explain);", connection, transaction)) { AddParameter(deckBuffCommand, "@GroupIdX"); AddParameter(deckBuffCommand, "@GroupName"); AddParameter(deckBuffCommand, "@Explain"); foreach (DeckBuffRecord record in package.DeckBuffs) { deckBuffCommand.Parameters["@GroupIdX"].Value = record.GroupIdX; deckBuffCommand.Parameters["@GroupName"].Value = record.GroupName; deckBuffCommand.Parameters["@Explain"].Value = record.Explain; deckBuffCommand.ExecuteNonQuery(); } } using (SqlCommand optionCommand = new(@" INSERT INTO [Asset].[DeckBuffOption] ([GroupIdX], [Condition], [AtType], [OptionId], [Value], [Prob], [Time]) VALUES (@GroupIdX, @Condition, @AtType, @OptionId, @Value, @Prob, @Time);", connection, transaction)) { AddParameter(optionCommand, "@GroupIdX"); AddParameter(optionCommand, "@Condition"); AddParameter(optionCommand, "@AtType"); AddParameter(optionCommand, "@OptionId"); AddParameter(optionCommand, "@Value"); AddParameter(optionCommand, "@Prob"); AddParameter(optionCommand, "@Time"); foreach (DeckBuffOptionRecord record in package.DeckBuffOptions) { optionCommand.Parameters["@GroupIdX"].Value = record.GroupIdX; optionCommand.Parameters["@Condition"].Value = record.Condition; optionCommand.Parameters["@AtType"].Value = record.AtType; optionCommand.Parameters["@OptionId"].Value = record.OptionId; optionCommand.Parameters["@Value"].Value = record.Value; optionCommand.Parameters["@Prob"].Value = record.Prob; optionCommand.Parameters["@Time"].Value = record.Time; optionCommand.ExecuteNonQuery(); } } transaction.Commit(); DigimonBookImportSummary summary = BuildSummary(package); summary = new DigimonBookImportSummary { BookInfoXmlRecordCount = summary.BookInfoXmlRecordCount, SyntheticBookInfoCount = summary.SyntheticBookInfoCount, DeckBuffRecordCount = summary.DeckBuffRecordCount, DeckBuffOptionRecordCount = summary.DeckBuffOptionRecordCount, EncyclopediaExceptionRecordCount = summary.EncyclopediaExceptionRecordCount, DeckCompositionRecordCount = summary.DeckCompositionRecordCount, DeletedDeckBookInfoCount = deletedDeckBookInfoCount, DeletedDeckBuffCount = deletedDeckBuffCount, DeletedDeckBuffOptionCount = deletedDeckBuffOptionCount, InsertedDeckBookInfoCount = package.BookInfos.Count, InsertedDeckBuffCount = package.DeckBuffs.Count, InsertedDeckBuffOptionCount = package.DeckBuffOptions.Count }; return summary; } catch { transaction.Rollback(); throw; } } private static DigimonBookImportSummary BuildSummary(DigimonBookImportPackage package) { return new DigimonBookImportSummary { BookInfoXmlRecordCount = package.BookInfoXmlRecordCount, SyntheticBookInfoCount = package.SyntheticBookInfoCount, DeckBuffRecordCount = package.DeckBuffs.Count, DeckBuffOptionRecordCount = package.DeckBuffOptions.Count, EncyclopediaExceptionRecordCount = package.EncyclopediaExceptionRecordCount, DeckCompositionRecordCount = package.DeckCompositionRecordCount }; } private static DigimonBookImportPackage LoadPackage( string bookInfoXmlPath, string deckOptionXmlPath, string encyclopediaExceptionXmlPath, string deckCompositionXmlPath) { List bookInfos = LoadBookInfos(bookInfoXmlPath, out int bookInfoXmlRecordCount, out int syntheticBookInfoCount); List deckBuffs = new(); List deckBuffOptions = new(); LoadDeckOptions(deckOptionXmlPath, deckBuffs, deckBuffOptions); return new DigimonBookImportPackage { BookInfos = bookInfos, BookInfoXmlRecordCount = bookInfoXmlRecordCount, SyntheticBookInfoCount = syntheticBookInfoCount, DeckBuffs = deckBuffs, DeckBuffOptions = deckBuffOptions, EncyclopediaExceptionRecordCount = CountRows(encyclopediaExceptionXmlPath, "EncyclopediaExceptionTable", "EncyclopediaException"), DeckCompositionRecordCount = CountRows(deckCompositionXmlPath, "DeckCompositionTable", "DeckComposition") }; } private static List LoadBookInfos(string xmlPath, out int xmlRecordCount, out int syntheticCount) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("BookInfo.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "BookInfoTable") { throw new InvalidOperationException("BookInfo.xml root node must be ."); } List records = new() { new DeckBookInfoRecord { OptionId = 0, Type = 0, Name = "None", Explain = "None." } }; syntheticCount = 1; xmlRecordCount = 0; foreach (XElement bookInfoElement in root.Elements("BookInfo")) { xmlRecordCount++; string recordContext = $"BookInfo row {xmlRecordCount}"; int optionId = ReadRequiredInt(bookInfoElement, "OptionId", recordContext); if (optionId < 1 || optionId > 6) { throw new InvalidOperationException($"{recordContext} has unsupported OptionId '{optionId}'. Current server enum expects values 1 through 6."); } records.Add(new DeckBookInfoRecord { OptionId = optionId, Type = optionId, Name = ReadRequiredTrimmedString(bookInfoElement, "OptionName", 200, recordContext), Explain = ReadOptionalTrimmedString(bookInfoElement, "OptionExplain", 200) }); } return records; } private static void LoadDeckOptions( string xmlPath, List deckBuffs, List deckBuffOptions) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("DeckOption.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "DeckOptionTable") { throw new InvalidOperationException("DeckOption.xml root node must be ."); } int rowIndex = 0; foreach (XElement deckOptionElement in root.Elements("DeckOption")) { rowIndex++; string recordContext = $"DeckOption row {rowIndex}"; int groupId = ReadRequiredInt(deckOptionElement, "GroupIndex", recordContext); deckBuffs.Add(new DeckBuffRecord { GroupIdX = groupId, GroupName = ReadRequiredTrimmedString(deckOptionElement, "GroupName", 250, recordContext), Explain = deckOptionElement.Element("Explain")?.Value?.Trim() ?? string.Empty }); List conditions = ReadTriplet(deckOptionElement, "Condition", recordContext); List atTypes = ReadTriplet(deckOptionElement, "AttackType", recordContext); List optionIds = ReadTriplet(deckOptionElement, "Option", recordContext); List optionValues = ReadTriplet(deckOptionElement, "OptionValue", recordContext); List probabilities = ReadTriplet(deckOptionElement, "Probability", recordContext); List times = ReadTriplet(deckOptionElement, "Time", recordContext); List records = BuildDeckBuffOptionRecords( groupId, conditions, atTypes, optionIds, optionValues, probabilities, times, recordContext); foreach (DeckBuffOptionRecord record in records) { deckBuffOptions.Add(record); } } } private static List BuildDeckBuffOptionRecords( int groupId, List conditions, List atTypes, List optionIds, List optionValues, List probabilities, List times, string recordContext) { List records = new(3); if (IsDeckBookOptionId(atTypes[2]) && optionIds[2] >= 0) { int prob = probabilities[0]; int time = times[0]; bool hasActivation = prob > 0 || time > 0; records.Add(new DeckBuffOptionRecord { GroupIdX = groupId, Condition = hasActivation ? BuildActivationCondition(time) : 1, AtType = hasActivation ? NormalizeAtType(conditions[2], recordContext) : 0, OptionId = atTypes[2], Value = optionIds[2], Prob = hasActivation ? prob : 0, Time = hasActivation ? time : 0 }); } AddDirectDeckBuffOptionRecord(records, groupId, 0, conditions, atTypes, optionIds, optionValues, probabilities, times, recordContext); AddDirectDeckBuffOptionRecord(records, groupId, 1, conditions, atTypes, optionIds, optionValues, probabilities, times, recordContext); while (records.Count < 3) { records.Add(new DeckBuffOptionRecord { GroupIdX = groupId, Condition = 0, AtType = 0, OptionId = 0, Value = 0, Prob = 0, Time = 0 }); } return records.Take(3).ToList(); } private static void AddDirectDeckBuffOptionRecord( List records, int groupId, int index, List conditions, List atTypes, List optionIds, List optionValues, List probabilities, List times, string recordContext) { int condition = conditions[index]; int optionId = optionIds[index]; if (condition == 0 || !IsDeckBookOptionId(optionId)) { return; } int atType = NormalizeAtType(atTypes[index], recordContext); int prob = probabilities[index]; int time = times[index]; if (condition == 1) { prob = 0; time = 0; } else if (prob == 0 && time == 0 && index + 1 < probabilities.Count) { prob = probabilities[index + 1]; time = times[index + 1]; } records.Add(new DeckBuffOptionRecord { GroupIdX = groupId, Condition = NormalizeCondition(condition, time, recordContext), AtType = atType, OptionId = optionId, Value = optionValues[index], Prob = prob, Time = time }); } private static bool IsDeckBookOptionId(int value) { return value >= 1 && value <= 6; } private static int BuildActivationCondition(int time) { return time > 0 ? 3 : 2; } private static int NormalizeCondition(int condition, int time, string recordContext) { if (condition < 0 || condition > 3) { throw new InvalidOperationException($"{recordContext} has unsupported deck buff condition '{condition}'."); } if (condition == 2 || condition == 3) { return BuildActivationCondition(time); } return condition; } private static int NormalizeAtType(int atType, string recordContext) { if (atType < 0 || atType > 2) { throw new InvalidOperationException($"{recordContext} has unsupported deck buff attack type '{atType}'."); } return atType; } private static int CountRows(string xmlPath, string expectedRootName, string elementName) { if (!File.Exists(xmlPath)) { return 0; } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != expectedRootName) { return 0; } return root.Elements(elementName).Count(); } private static List ReadTriplet(XElement parent, string containerElementName, string recordContext) { XElement? container = parent.Element(containerElementName); if (container == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{containerElementName}'."); } List values = container.Elements("Value") .Select((element, index) => ReadIntValue(element, $"{recordContext}, {containerElementName}[{index + 1}]")) .ToList(); if (values.Count != 3) { throw new InvalidOperationException($"{recordContext} must contain exactly 3 values in '{containerElementName}', but found {values.Count}."); } return values; } private static int ReadIntValue(XElement element, string recordContext) { if (!int.TryParse(element.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) { throw new InvalidOperationException($"{recordContext} has invalid integer value '{element.Value}'."); } return value; } 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 ReadRequiredTrimmedString(XElement parent, string elementName, int maxLength, string recordContext) { string value = ReadOptionalTrimmedString(parent, elementName, maxLength); if (string.IsNullOrWhiteSpace(value)) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } return value; } private static string ReadOptionalTrimmedString(XElement parent, string elementName, int maxLength) { string value = parent.Element(elementName)?.Value?.Trim() ?? string.Empty; return value.Length <= maxLength ? value : value.Substring(0, maxLength); } private static int ExecuteScalarInt(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); object? result = command.ExecuteScalar(); return Convert.ToInt32(result, CultureInfo.InvariantCulture); } private static void ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); command.ExecuteNonQuery(); } private static void AddParameter(SqlCommand command, string name) { command.Parameters.Add(new SqlParameter(name, DBNull.Value)); } private sealed class DigimonBookImportPackage { public List BookInfos { get; init; } = new(); public int BookInfoXmlRecordCount { get; init; } public int SyntheticBookInfoCount { get; init; } public List DeckBuffs { get; init; } = new(); public List DeckBuffOptions { get; init; } = new(); public int EncyclopediaExceptionRecordCount { get; init; } public int DeckCompositionRecordCount { get; init; } } private sealed class DeckBookInfoRecord { public int OptionId { get; init; } public int Type { get; init; } public string Name { get; init; } = string.Empty; public string Explain { get; init; } = string.Empty; } private sealed class DeckBuffRecord { public int GroupIdX { get; init; } public string GroupName { get; init; } = string.Empty; public string Explain { get; init; } = string.Empty; } private sealed class DeckBuffOptionRecord { public int GroupIdX { get; init; } public int Condition { get; init; } public int AtType { get; init; } public int OptionId { get; init; } public int Value { get; init; } public int Prob { get; init; } public int Time { get; init; } } } }