using System.Text.Json;
using System.Text.RegularExpressions;
using System.Xml;

namespace IS_Lab2_XMLJson;

public class XmlJsonConverter
{
    public static string SanitizeTag(string tag)
    {
        return Regex.Replace(tag, @"[^a-zA-Z0-9_-]", "_");
    }
    
    public static void JsonToXml(string jsonFile, string xmlOutput)
    {
        var jsonText = File.ReadAllText(jsonFile);
        var objs = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonText)!;

        var doc = new XmlDocument();
        var root = doc.CreateElement("Jednostki");
        doc.AppendChild(root);
        
        foreach (var obj in objs)
        {
            var elem = doc.CreateElement("Jednostka");
            foreach (var pair in obj)
            {
                var pairObject = doc.CreateElement(SanitizeTag(pair.Key));
                pairObject.InnerText = pair.Value?.ToString() ?? "";

                elem.AppendChild(pairObject);
            }

            root.AppendChild(elem);
        }

        File.WriteAllText(xmlOutput, doc.OuterXml);
    }
    
    public static void XmlToJson(string xmlFile, string jsonOutput)
    {
        var doc = new XmlDocument();
        doc.Load(xmlFile);

        var root = doc.DocumentElement!;
        var units = new List<Dictionary<string, object>>();

        foreach (XmlNode unitNode in root.ChildNodes)
        {
            var unitDict = new Dictionary<string, object>();
            foreach (XmlNode childNode in unitNode.ChildNodes)
                unitDict[childNode.Name] = childNode.InnerText;
            
            units.Add(unitDict);
        }

        var jsonText = JsonSerializer.Serialize(units, new JsonSerializerOptions { WriteIndented = true });
        File.WriteAllText(jsonOutput, jsonText);
    }
}