// include sql-formatter-min.js
/**
 * Above include will include minified version of sql-formatter library.
 * github-link: https://github.com/sql-formatter-org/sql-formatter
 * version: 12.2.4
 * last updated 29th Aug 2023
 */

function OnInit() {
    UltraEdit.processPIOnInit(`{
        "guid": "f620c8f5-77a5-4aa7-9560-215e3c734d33",
        "ueplFormatSQL": {
            "type": "Execute",
            "display name": "Format SQL",
            "short description": "SQL formatter",
            "icon": "",
            "hotkey": "Ctrl + [",
            "chord": "Ctrl + F"
        }
    }`);
}

/**
 * @def This function will allow users to format SQL files into mysql format.
 * @desc In this plugin we have used a 3rd party library sql-formater (more details about the library mentioned in sqlFormatter fn desc)
 * using sql-formatter format function the selected text or whole file will be formatted.
 */
function ueplFormatSQL() {
    /* Conditions and Error Handaling are prefixed with appropiate keyWork */
    
    /* ----------------------------- 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("SQL Formatter Plugin Error", "There is no active document to format SQL");
        return;
    };
    /* ---------------------------------------------------------------------------- */

    /* ------------------------- Process SQL Formatting ---------------------------- */
    // Const & State
    const WorkingDocument = UltraEdit.document[UltraEdit.activeDocumentIdx];
    // const formatOptions = {
    //     language: 'mysql',
    //     keywordCase: 'upper',
    //     linesBetweenQueries: 2,
    // };
    let isSelected = true;
    let invalidTextError = 'Selected text contains invalid SQL syntax. Please select valid SQL syntax.';
    let formatedSQL = ''

    // Check if something is selected on activeDocument, if not prepare proper values.
    if (!WorkingDocument.isSel()) {
        WorkingDocument.selectAll();
        isSelected = false;
        invalidTextError = 'File contains invalid SQL syntax. Please select valid SQL syntax.';
    }

    // state to mantain selected text
    const textToFormater = WorkingDocument.selection;
    
    // try to format selected SQL...
    try {
        formatedSQL = this.sqlFormatter.format(textToFormater);
    } catch {
        handleError("SQL Formatting Plugin Error", invalidTextError);
        return;
    }
    
    /* ---- Replace Text */
    WorkingDocument.deleteText();
    WorkingDocument.write(formatedSQL);

    /* ---------------------------------------------------------------------------- */
}

/**
 * Helper function to show formated error to a user.
 * It shows a dialog box and shows error in output window if provided
 * @param {string} title 
 * @param {string} titleDesc 
 * @param {string} outputText 
 */
function handleError(title, titleDesc, outputText = `SQL Formatter Plugin Error -> ${titleDesc}`) {
    UltraEdit.messageBox(titleDesc, title);
    UltraEdit.outputWindow.write(outputText);
}
