using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DwgExtractorManual.Models
{
///
/// JSON ÆÄÀÏ Ã³¸® ¹× ¸ÅÇÎ µ¥ÀÌÅÍ °ü¸®¸¦ ´ã´çÇϴ Ŭ·¡½º
///
internal class JsonDataProcessor
{
///
/// JSON ÆÄÀÏ¿¡¼ PDF ºÐ¼® °á°ú¸¦ ÀÐ¾î ¸ÅÇÎ µ¥ÀÌÅ͸¦ ¾÷µ¥ÀÌÆ®
///
public bool UpdateMappingDataFromJson(Dictionary> mappingData, string jsonFilePath)
{
try
{
Debug.WriteLine($"[DEBUG] JSON ÆÄÀÏ¿¡¼ PDF °ª ¾÷µ¥ÀÌÆ® ½ÃÀÛ: {jsonFilePath}");
if (!File.Exists(jsonFilePath))
{
Debug.WriteLine($"? JSON ÆÄÀÏÀÌ Á¸ÀçÇÏÁö ¾Ê½À´Ï´Ù: {jsonFilePath}");
return false;
}
// JSON ÆÄÀÏ ÀÐ±â ¹× Á¤¸®
string jsonContent = File.ReadAllText(jsonFilePath, System.Text.Encoding.UTF8);
jsonContent = CleanJsonContent(jsonContent);
JObject jsonData;
try
{
jsonData = JObject.Parse(jsonContent);
}
catch (Newtonsoft.Json.JsonReaderException jsonEx)
{
Debug.WriteLine($"? JSON ÆÄ½Ì ¿À·ù: {jsonEx.Message}");
throw new System.Exception($"PDF ºÐ¼® JSON ÆÄÀÏ ÆÄ½Ì ½ÇÆÐ: {jsonEx.Message}\nÆÄÀÏ: {jsonFilePath}");
}
var results = jsonData["results"] as JArray;
if (results == null)
{
Debug.WriteLine("? JSON¿¡¼ 'results' ¹è¿À» ãÀ» ¼ö ¾ø½À´Ï´Ù.");
return false;
}
int updatedCount = 0;
int totalEntries = 0;
foreach (JObject result in results)
{
var fileInfo = result["file_info"];
var pdfAnalysis = result["pdf_analysis"];
if (fileInfo == null || pdfAnalysis == null) continue;
string fileName = fileInfo["name"]?.ToString();
if (string.IsNullOrEmpty(fileName)) continue;
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);
if (!mappingData.ContainsKey(fileNameWithoutExt))
{
Debug.WriteLine($"?? ¸ÅÇÎ µ¥ÀÌÅÍ¿¡ ÆÄÀÏÀÌ ¾ø½À´Ï´Ù: {fileNameWithoutExt}");
continue;
}
foreach (var property in pdfAnalysis.Cast())
{
string aiLabel = property.Name;
var valueObj = property.Value as JObject;
if (valueObj == null) continue;
string pdfValue = valueObj["value"]?.ToString();
if (string.IsNullOrEmpty(pdfValue)) continue;
totalEntries++;
var fileData = mappingData[fileNameWithoutExt];
var matchingEntry = fileData.FirstOrDefault(kvp =>
string.Equals(kvp.Value.Item1.Trim(), aiLabel.Trim(), StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(matchingEntry.Key))
{
var existingValue = matchingEntry.Value;
fileData[matchingEntry.Key] = (existingValue.Item1, existingValue.Item2, existingValue.Item3, pdfValue);
updatedCount++;
}
}
}
Debug.WriteLine($"[DEBUG] PDF µ¥ÀÌÅÍ ¾÷µ¥ÀÌÆ® ¿Ï·á: {updatedCount}/{totalEntries} ¾÷µ¥ÀÌÆ®µÊ");
return true;
}
catch (System.Exception ex)
{
Debug.WriteLine($"? JSON¿¡¼ PDF °ª ¾÷µ¥ÀÌÆ® Áß ¿À·ù: {ex.Message}");
return false;
}
}
///
/// ¸ÅÇÎ µñ¼Å³Ê¸®¸¦ JSON ÆÄÀÏ·Î ÀúÀå
///
public void SaveMappingDictionary(Dictionary> mappingData, string filePath)
{
try
{
Debug.WriteLine($"[DEBUG] ¸ÅÇÎ µñ¼Å³Ê¸® ÀúÀå ½ÃÀÛ: {filePath}");
var serializableData = new Dictionary>();
foreach (var fileEntry in mappingData)
{
var fileData = new Dictionary();
foreach (var mapEntry in fileEntry.Value)
{
fileData[mapEntry.Key] = new
{
AILabel = mapEntry.Value.Item1,
DwgTag = mapEntry.Value.Item2,
DwgValue = mapEntry.Value.Item3,
PdfValue = mapEntry.Value.Item4
};
}
serializableData[fileEntry.Key] = fileData;
}
string jsonContent = JsonConvert.SerializeObject(serializableData, Formatting.Indented);
File.WriteAllText(filePath, jsonContent, System.Text.Encoding.UTF8);
Debug.WriteLine($"? ¸ÅÇÎ µñ¼Å³Ê¸® ÀúÀå ¿Ï·á: {Path.GetFileName(filePath)}");
Debug.WriteLine($"?? ÀúÀåµÈ ÆÄÀÏ ¼ö: {mappingData.Count}");
}
catch (System.Exception ex)
{
Debug.WriteLine($"? ¸ÅÇÎ µñ¼Å³Ê¸® ÀúÀå Áß ¿À·ù: {ex.Message}");
throw;
}
}
///
/// JSON ÆÄÀÏ¿¡¼ ¸ÅÇÎ µñ¼Å³Ê¸®¸¦ ·Îµå
///
public Dictionary> LoadMappingDictionary(string filePath)
{
var result = new Dictionary>();
try
{
Debug.WriteLine($"[DEBUG] ¸ÅÇÎ µñ¼Å³Ê¸® ·Îµå ½ÃÀÛ: {filePath}");
if (!File.Exists(filePath))
{
Debug.WriteLine($"?? ¸ÅÇÎ ÆÄÀÏÀÌ Á¸ÀçÇÏÁö ¾Ê½À´Ï´Ù: {filePath}");
return result;
}
string jsonContent = File.ReadAllText(filePath, System.Text.Encoding.UTF8);
jsonContent = CleanJsonContent(jsonContent);
Dictionary> deserializedData;
try
{
deserializedData = JsonConvert.DeserializeObject>>(jsonContent);
}
catch (Newtonsoft.Json.JsonReaderException jsonEx)
{
Debug.WriteLine($"? JSON ÆÄ½Ì ¿À·ù: {jsonEx.Message}");
throw new System.Exception($"¸ÅÇÎ JSON ÆÄÀÏ ÆÄ½Ì ½ÇÆÐ: {jsonEx.Message}\nÆÄÀÏ: {filePath}");
}
if (deserializedData != null)
{
foreach (var fileEntry in deserializedData)
{
var fileData = new Dictionary();
foreach (var mapEntry in fileEntry.Value)
{
var valueObj = mapEntry.Value;
string aiLabel = valueObj["AILabel"]?.ToString() ?? "";
string dwgTag = valueObj["DwgTag"]?.ToString() ?? "";
string dwgValue = valueObj["DwgValue"]?.ToString() ?? "";
string pdfValue = valueObj["PdfValue"]?.ToString() ?? "";
fileData[mapEntry.Key] = (aiLabel, dwgTag, dwgValue, pdfValue);
}
result[fileEntry.Key] = fileData;
}
}
Debug.WriteLine($"? ¸ÅÇÎ µñ¼Å³Ê¸® ·Îµå ¿Ï·á");
Debug.WriteLine($"?? ·ÎµåµÈ ÆÄÀÏ ¼ö: {result.Count}");
return result;
}
catch (System.Exception ex)
{
Debug.WriteLine($"? ¸ÅÇÎ µñ¼Å³Ê¸® ·Îµå Áß ¿À·ù: {ex.Message}");
throw;
}
}
///
/// JSON ³»¿ëÀ» Á¤¸®ÇÏ¿© ÆÄ½Ì °¡´ÉÇÑ »óÅ·Π¸¸µì´Ï´Ù.
///
private string CleanJsonContent(string jsonContent)
{
if (string.IsNullOrEmpty(jsonContent))
return jsonContent;
try
{
var lines = jsonContent.Split('\n');
var cleanedLines = new List();
bool inMultiLineComment = false;
foreach (string line in lines)
{
string processedLine = line;
// ¸ÖƼ¶óÀÎ ÁÖ¼® ó¸®
if (inMultiLineComment)
{
int endIndex = processedLine.IndexOf("*/");
if (endIndex >= 0)
{
processedLine = processedLine.Substring(endIndex + 2);
inMultiLineComment = false;
}
else
{
continue;
}
}
int multiLineStart = processedLine.IndexOf("/*");
if (multiLineStart >= 0)
{
int multiLineEnd = processedLine.IndexOf("*/", multiLineStart + 2);
if (multiLineEnd >= 0)
{
processedLine = processedLine.Substring(0, multiLineStart) +
processedLine.Substring(multiLineEnd + 2);
}
else
{
processedLine = processedLine.Substring(0, multiLineStart);
inMultiLineComment = true;
}
}
// ½Ì±Û¶óÀÎ ÁÖ¼® Á¦°Å
bool inString = false;
bool escaped = false;
int commentIndex = -1;
for (int i = 0; i < processedLine.Length - 1; i++)
{
char current = processedLine[i];
char next = processedLine[i + 1];
if (escaped)
{
escaped = false;
continue;
}
if (current == '\\')
{
escaped = true;
continue;
}
if (current == '"')
{
inString = !inString;
continue;
}
if (!inString && current == '/' && next == '/')
{
commentIndex = i;
break;
}
}
if (commentIndex >= 0)
{
processedLine = processedLine.Substring(0, commentIndex);
}
if (!string.IsNullOrWhiteSpace(processedLine))
{
cleanedLines.Add(processedLine);
}
}
return string.Join("\n", cleanedLines);
}
catch (System.Exception ex)
{
Debug.WriteLine($"? JSON Á¤¸® Áß ¿À·ù: {ex.Message}");
return jsonContent;
}
}
}
}