#!/usr/bin/env python
import argparse
from json import load
from dicttoxml import dicttoxml
from pathlib import Path
from xml.dom.minidom import parseString

"""
Script to format a JSON file to its corresponding XML representation.

Based on the following references: 
    https://stackoverflow.com/questions/8988775/convert-json-to-xml-in-python
    https://github.com/quandyfactory/dicttoxml

Dependencies:
    pip3 install dicttoxml
"""

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Format a JSON file to its corresponding XML representation.")
    required_params = parser.add_argument_group("required named arguments")
    required_params.add_argument("-i", action="store", dest="json_file", help="Path to the JSON file to convert.", required=True)
    parser.add_argument("-o", action="store", dest="xml_file", help="Path to the converted XML file (default to source file name but with extension changed).", required=False, default=None)
    parser.add_argument("-p", action="store_true", dest="pretty_print", help="Pretty print the XML (default to False).", required=False, default=False)
    args = parser.parse_args()
    json_file = args.json_file
    xml_file = args.xml_file
    if xml_file is None:
        xml_file = f"{Path(json_file).stem}.xml"
    print(f"[+] Convert file '{json_file}' to '{xml_file}'...")
    with open(json_file, mode="r", encoding="utf-8") as f:
        json_data = load(f)
    xml = dicttoxml(json_data, attr_type=False).decode("utf-8")
    if args.pretty_print:
        xml = parseString(xml).toprettyxml()
    with open(xml_file, mode="w", encoding="utf-8") as f:
        f.write(xml)
    print(f"[+] Convertion finished.")
