// This code is mostly written for windows and not tested on other OS

function OnInit() {
    UltraEdit.processPIOnInit(`{
        "guid": "d7e3a2b2-5180-415c-b1c2-7e433d2f8e49",
        "SplitFile": {
            "type": "Execute",
            "display name": "Split File",
            "short description": "Large file splitter",
            "icon": "",
            "hotkey": "Ctrl + [",
            "chord": "Ctrl + S"
        }        
    }`);
}

/**
 * @def This function will allow user to split a active file into multiple small files according to the input.
 * @desc Ones this plugin is called it will ask user for a numeric input, which will be number of lines user wants to store in a split file.
 * Further this input will be used to split a large file into small managble chunks
 */
function SplitFile() {
    /* Conditions and Error Handaling are prefixed with appropiate keyWork */

    // setup working env
    const WorkingDocument = UltraEdit.document[UltraEdit.activeDocumentIdx];
    /* ----------------------------- 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 || !WorkingDocument.path) {
        handleError("Split File Plugin Error", "There is no active document to split.");
        return;
    };
    // Handle Error if its a temp file 
    if (!WorkingDocument.path.includes('\\') && WorkingDocument.path.includes('Edit')) {
      handleError("Split File Plugin Error", "Cannot split temp file. Save the temp file and try again.");
        return;
    }
    /* ---------------------------------------------------------------------------- */

    /* ------------------------- Process File Spliting ---------------------------- */
    // Go to bottom of file to check the last line number.
    UltraEdit.activeDocument.bottom();
    const lastLineNumberOfFile = UltraEdit.activeDocument.currentLineNum;

    // store user input
    let numberOfLines = UltraEdit.getValue("Specify the desired number of lines for file segmentation", 1);

    /* ----------------- Handle Input Error --------- */
    // Return if value is empty (user clicked cancle button)
    if (numberOfLines === "") return;
    else numberOfLines = +numberOfLines;
    // --- Stop process if given number is less than or 0
    if (numberOfLines <= 0) {
        handleError("Split File Plugin Error", "Specify number greater than 0");
        return;
    }
    // --- Stop process if given number exeeds current file length
    if (numberOfLines > lastLineNumberOfFile) {
        handleError("Split File Plugin Error", "Specified number is greater than the current document length");
        return;
    }

    // save old clipbordIndex, setup clipboard 9 for using file copy / paste
    const initialClipBoard = UltraEdit.clipboardIdx
    UltraEdit.selectClipboard(9);
    // setup variables for the process
    let numberOfFiles = 0;
    let nextLineNumber = numberOfLines + 1;
    const maxFiles = Math.floor(lastLineNumberOfFile / numberOfLines) + (lastLineNumberOfFile % numberOfLines > 0 ? 1 : 0);

    // setup filename
    let lastIndexOfDot = WorkingDocument.path.lastIndexOf('.');
    if (lastIndexOfDot < 0) lastIndexOfDot = WorkingDocument.path.length;
    const fileNameWithFullPath = WorkingDocument.path.substr(0, lastIndexOfDot);
    const fileExtention = WorkingDocument.path.substr(lastIndexOfDot);

    // start from the top of file
    WorkingDocument.top();

    // ------------ Logic to create new files
    while(true) {
        WorkingDocument.gotoLineSelect(nextLineNumber, 1);
        // fail safe // loop break
        if (!WorkingDocument.isSel()) break;
        if (numberOfFiles >= maxFiles) break;

        // Copy the selected block to user clipboard 9.
        WorkingDocument.copy();
        WorkingDocument.cancelSelect();

        /*
            Prepare new FileName
            Open New File, start writing to the new File, then save and close the file.
        */
        const newFileName = `${fileNameWithFullPath}${numberOfFiles}${fileExtention}`;
        UltraEdit.newFile();
        UltraEdit.outputWindow.write(`Writing chunk to new file at ${newFileName}`);
        UltraEdit.activeDocument.paste();
        UltraEdit.saveAs(newFileName);
        UltraEdit.closeFile(UltraEdit.activeDocument.path, 2);

        // prepare next file values
        numberOfFiles++;
        nextLineNumber += numberOfLines;
    }

    // clear up memory and settings
    UltraEdit.clearClipboard();
    UltraEdit.selectClipboard(initialClipBoard);
    UltraEdit.outputWindow.write(`${numberOfFiles} files created Successfully.`);
    WorkingDocument.top();
    /* --------------------------------------------------------------------- */
}

/**
 * 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 = `Split File Plugin Error -> ${titleDesc}`) {
    UltraEdit.messageBox(titleDesc, title);
    UltraEdit.outputWindow.write(outputText);
}
