// include json-to-xml.js

function OnInit() {
    UltraEdit.processPIOnInit(`{
        "guid": "e7df8434-ad05-4bfb-ac61-50defd619336",
        "ueplJSONtoXML": {
            "type": "Execute",
            "display name": "Convert JSON to XML",
            "short description": "JSON to XML converter",
            "icon": "",
            "hotkey": "Ctrl + [",
            "chord": "Ctrl + J"
        }
    }`);
}

function ueplJSONtoXML() {
    const config = {
        indent: '  '
    };
    /* ----------------------------- Error Handling ------------------------------- */
    /*
    // Check if there are documents on editor and check if they are active
    // if not active show error and stop the process.
    */

    if (UltraEdit.document.length < 1 || !UltraEdit.activeDocument.path) {
        handleError("JSON to XML Plugin Error", "There is no active JSON document to convert to XML.");
        return;
    };
    const clip = UltraEdit.activeDocument.selection;

    // if there is no data is selected then select all the data 
    if (!UltraEdit.activeDocument.isSel()) {
        UltraEdit.activeDocument.selectAll();
    const text = UltraEdit.activeDocument.selection
    try {
        const parseClipData = JSON.parse(`${text}`);
        const xmlResult = toXML(parseClipData, config);
        UltraEdit.activeDocument.write(xmlResult)    
    } catch (e) {
        handleError("JSON to XML Plugin Error", "Selected data does not contain vaild JSON.")
    }
    } else {
        {
             try { 
                const parseClipData = JSON.parse(`${clip}`);
                const xmlResult = toXML(parseClipData, config);
                 UltraEdit.activeDocument.write(xmlResult)    
                } catch (e) {
                    handleError("JSON to XML Plugin Error", "Selected data does not contain vaild JSON.")
                }

    };
}
}

 /**
 * Helper function to show formated error to a user.
 * It shows a dialog box
 * */

function handleError(title,description){
    UltraEdit.messageBox(description, title)
    UltraEdit.outputWindow.write(`Json to Xml plugin -> ${description}`);
}
