//
// To execute:
//
//    CScript CreateUnit.js
//

// ==== Initialisation =====================================================

var WshShell = WScript.CreateObject("WScript.Shell");
var WshProEnv = WshShell.Environment("SYSTEM");

var XomLocation = WshProEnv.Item("XOM");
var UnitName, UnitNameUpper;
var UnitGuid;

var fso = new ActiveXObject("Scripting.FileSystemObject");

// ==== Support Functions ==================================================

function MakeUuid()
{
    var aJob = WshShell.Exec("uuidgen");

    // Wait for command to finish

    while(aJob.Status == 0);

    // Get uuid emitted from uuidgen.exe

    var line = aJob.StdOut.ReadLine();

    // Reformat it into a C++ macro argument

    var cppUuid = "0x" + line.substr(0, 8);

    cppUuid += ", 0x" + line.substr(9,4);
    cppUuid += ", 0x" + line.substr(14,4);

    cppUuid += ", 0x" + line.substr(19,2);
    cppUuid += ", 0x" + line.substr(21,2);

    for (var n = 0; n < 6; n++) {
        cppUuid += ", 0x" + line.substr(24 + n * 2, 2);
    }

    return cppUuid;
}

function ReplaceInString(input, match, replace)
{
    var out = "";
    var re = new RegExp(match, "g");
    var start = 0;

    var arr;
    while ((arr = re.exec(input)) != null) {
        if (arr.index > start) {
            out += input.substr(start, arr.index - start);
        }

        start = arr.lastIndex;
        out += replace;
    }

    if (start < input.length) {
        out += input.substr(start, input.length - start);
    }

    return out;
}

function FilterFile(inputFileName)
{
    var output = "";
    var file;

    // Open input file

    try {
        file = fso.OpenTextFile(inputFileName, 1);
    } catch(e) {
        WScript.echo("ERROR: Failed to open input file - exception = " + e + "\n");
        WScript.quit(4);
    }

    // Filter line by line until EOF

    while(!file.AtEndOfStream) {
        var line = file.ReadLine();

        line = ReplaceInString(line, "XImageIo", UnitName);
        line = ReplaceInString(line, "XIMAGEIO", UnitNameUpper);
        line = ReplaceInString(line, "_UnitGUID_", UnitGuid);

        output += line + "\r\n";
   }

   return output;
}


// ================================== Main =================================

var objArgs = WScript.Arguments;

if (objArgs.Count() != 1) {
   WScript.echo("Usage: CreateUnit <unitname>");

   WScript.Quit(1);
}

WScript.echo("XOM Location = " + XomLocation);

UnitName = objArgs.Item(0);
UnitNameUpper = UnitName.toUpperCase();
UnitGuid = MakeUuid();

var BtnCode = WshShell.Popup("This will create a directory named '" + UnitName + 
                             "' in the XOM base directory\n" +
                             "and create a template XOM Unit project there.\n\n" +
                             "Do you want to continue?", 0, "Create Unit Confirmation", 1 + 32);

if (BtnCode == 2) {
   WScript.echo("Operation cancelled.\n");
   WScript.quit(2);
}

WScript.echo("\n" + "Creating skeleton for unit '" + UnitName + "'");

// Create folder

var unitPath = fso.BuildPath(XomLocation, UnitName);

try {
  fso.CreateFolder(unitPath);
} catch(e) {
  WScript.echo("ERROR: Folder '" + unitPath + "' aldready exists.\n");
  WScript.quit(3);
}

// Generate array of template file names

var folder = fso.GetFolder(XomLocation + "/Templates/Unit");
var fileEnumerator = new Enumerator(folder.files);
var templateFiles = new Array();

while(!fileEnumerator.atEnd()) {
   templateFiles[fileEnumerator.item()] = "<empty>";

   fileEnumerator.moveNext();
}

// Filter templates

var fileName;

for (fileName in templateFiles) {
   templateFiles[fileName] = FilterFile(fileName);
}

// Emit files

for (fileName in templateFiles) {
   // Get filename

   var outFileName = fso.BuildPath(unitPath, fso.GetFileName(ReplaceInString(fileName, "XImageIo", UnitName)));
   WScript.echo("Emitting: " + outFileName);
   var outFile = fso.CreateTextFile(outFileName, true);

   outFile.Write(templateFiles[fileName]);

   outFile.close();
}
