use crate::xml_utils::{write_declaration, write_comment, write_start_tag, write_empty_tag, write_end_tag, write_content};
use std::fs;
use quick_xml::Writer;
use quick_xml::events::{BytesEnd, BytesStart};
use serde_json::{Value, Map, from_str};
use std::collections::HashMap;
use std::io::Cursor;
pub fn json_to_xml(json_string: &str, root: &str) -> String {
let json_value: Value = from_str(&json_string).unwrap();
let mut writer = Writer::new_with_indent(Cursor::new(Vec::new()), b' ', 2);
write_declaration(&mut writer, "1.0", Some("UTF-8"));
let mut version = get_dependency_version("Cargo.toml").unwrap_or("0.0.0".to_string());
version = format!("Generated with json_to_xml {}", version);
write_comment(&mut writer, &version);
create_xml_element(&json_value, &mut writer, root);
if has_top_level_attributes(&json_value) {
write_end_tag(&mut writer, &BytesEnd::new(root));
}
String::from_utf8(writer.into_inner().into_inner()).expect("Failed to convert to UTF-8")
}
pub fn get_dependency_version(file_path: &str) -> Option<String> {
let content = fs::read_to_string(file_path).expect("Unable to read the file");
let toml: Value = toml::de::from_str(&content).expect("Unable to parse TOML");
toml.get("dependencies")
.and_then(|deps| deps.get("json_to_xml"))
.and_then(|dep| {
if dep.is_object() {
dep.get("version").and_then(|v| v.as_str()).map(|s| s.to_string())
} else {
dep.as_str().map(|s| s.to_string())
}
})
}
fn create_xml_element(
json_data: &Value,
writer: &mut Writer<Cursor<Vec<u8>>>,
parent_tag: &str
) {
match json_data {
Value::Object(map) => {
handle_object(writer, map, parent_tag);
},
Value::Array(arr) => {
handle_array(writer, arr, parent_tag);
},
Value::String(s) => {
write_content(writer, s);
},
Value::Number(num) => {
write_content(writer, &num.to_string());
}
Value::Bool(b) => {
write_content(writer, &b.to_string());
}
Value::Null => {
write_empty_tag(writer, &BytesStart::new(parent_tag));
}
}
}
fn handle_object(writer: &mut Writer<Cursor<Vec<u8>>>, map: &Map<String, Value>, parent_tag: &str) {
let parent_tag = capitalize_word(parent_tag);
let mut element = BytesStart::new(parent_tag);
let attributes: HashMap<_, _> = map
.iter()
.filter(|(key, _)| key.starts_with("@"))
.map(|(key, value)| (&key[1..], value))
.collect();
for (key, value) in &attributes {
if let Some(value_str) = value.as_str() {
element.push_attribute((*key, value_str));
}
}
if !attributes.is_empty() {
write_start_tag(writer, &element);
}
if map.contains_key("$text") {
let text_content = map.get("$text").unwrap().as_str().unwrap();
write_content(writer, text_content);
}
for (key, value) in map {
let key_tag = capitalize_word(key);
element = BytesStart::new(key_tag.clone());
if value.is_object() && value.as_object().unwrap().is_empty() {
write_empty_tag(writer, &element);
continue;
}
if key.starts_with("@") || key == "$text" {
continue;
} else {
if !(is_attribute_key(value) || is_array_with_attribute_key(value)) {
write_start_tag(writer, &element);
}
create_xml_element(value, writer, key);
if !value.is_array() {
write_end_tag(writer, &BytesEnd::new(key_tag));
}
}
}
}
fn handle_array(writer: &mut Writer<Cursor<Vec<u8>>>, arr: &Vec<Value>, parent_tag: &str) {
let mut parent_tag = capitalize_word(parent_tag);
if arr.is_empty() {
write_empty_tag(writer, &BytesStart::new(&parent_tag));
return;
}
let original_tag = parent_tag.clone();
for (i, value) in arr.iter().enumerate() {
if value.is_object() {
handle_object_array(writer, i, value, &parent_tag);
} else {
write_start_tag(writer, &BytesStart::new(&parent_tag));
create_xml_element(value, writer, &original_tag);
write_end_tag(writer, &BytesEnd::new(&parent_tag));
if i == arr.len() - 1 {
write_end_tag(writer, &BytesEnd::new(&original_tag));
}
}
}
}
fn handle_object_array(
writer: &mut Writer<Cursor<Vec<u8>>>,
index: usize,
value: &Value,
parent_tag: &str
) {
let first_key = value.as_object().unwrap().keys().next().unwrap();
if !first_key.starts_with("@") && index > 0 {
write_start_tag(writer, &BytesStart::new(parent_tag));
}
create_xml_element(value, writer, &parent_tag);
write_end_tag(writer, &BytesEnd::new(parent_tag));
}
fn has_top_level_attributes(json: &Value) -> bool {
if let Value::Object(map) = json {
map.keys().any(|key| key.starts_with('@'))
} else {
false
}
}
fn is_attribute_key(value: &Value) -> bool {
value.is_object()
&& value.as_object()
.unwrap()
.keys()
.any(|key| key.starts_with("@")) }
fn is_array_with_attribute_key(value: &Value) -> bool {
value.is_array()
&& value.as_array()
.unwrap()
.first()
.map(|v| is_attribute_key(v))
.unwrap_or(false)
}
fn capitalize_word(word: &str) -> String {
let mut chars = word.chars();
match chars.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
}
}