/**
 * ~/.jedit/startup/startup.js
 */

var 
	jEdit = org.gjt.sp.jedit.jEdit,
	Macros = org.gjt.sp.jedit.Macros,
	System = java.lang.System;

//------------------------------------------------------------------------------
	
var
	STARTUP = {version: 1},
	DS = "/",
	DOTJEDITPATH = "Q:/.jedit/",
	OS = "windows";

if (System.getProperty("os.name").indexOf("Windows") == -1) { 
	DS = "/";
	DOTJEDITPATH = "~/.jedit/";
	OS = "linux";
}

var
	//a directory called "out" in the settings directory for dumping things
	OUTPATH = DOTJEDITPATH + "out" + DS,
	
	//macro libs I don't want to see in the Macros menu (use with require/include)
	MACROLIBPATH = DOTJEDITPATH + "macros_libs" + DS;


//------------------------------------------------------------------------------
//PROTOTYPES


//Array indexOf fix by boothby
[].indexOf || (Array.prototype.indexOf = function(v,n){
	n = (n == null) ? 0 : n;
	var m = this.length;
	for (var i = n; i < m; i++)
		if (this[i] == v) return i;
	return -1;
});


//------------------------------------------------------------------------------
//JAVASCRIPTSHELL HELPER UTILS


//are you looking for a plugin to be used in a macro?
listPlugins = function(){//{{{
	var plugs = org.gjt.sp.jedit.jEdit.getPlugins();
	jsConsole.log("\n=== plugin classNames ===");
	for (var i in plugs){
		if (plugs[i].getClassName) jsConsole.log(plugs[i].getClassName());
	}
}//}}}


//------------------------------------------------------------------------------
//PHP-ISH


function file_exists(filename){//{{{
	var f = new java.io.File(filename);
	return f.exists();
}//}}}


function require(filename) {//{{{
	if (!file_exists(filename)){
		alert("File doesn't exist:\n" + filename);
		return false;
	}
	if (Macros.getHandler("JavaScriptHandler").accept(filename)) {
		Macros.runScript(view, filename, false);
	} else {
		alert("Not a javascript macro:\n" + filename);
		return false;
	}
}
var include = require; 
//}}}


function require_once(filename){//{{{
	if (!require_once.__requiredFiles) {
		require_once.__requiredFiles = [];
	}
	if (require_once.__requiredFiles.indexOf(filename) > -1) {
		return false;
	} else {
		include(filename);
		require_once.__requiredFiles.push(filename);
		return true;
	}
};//}}}


function file_get_contents(filename) {//{{{
	var s = "",
		ret = "",
		fr = new java.io.FileReader(filename),
		br = new java.io.BufferedReader(fr);
	while((s = br.readLine()) != null) { ret += s + "\n"; }
	fr.close();
	return ret;
}//}}}


function file_put_contents(filename, data) {//{{{
	var append = false,
		fw = new java.io.FileWriter(filename, append);
	fw.write(text);
	fw.close();
}//}}}


function system(command) {//{{{
	jsConsole.open();
	var c = jsConsole.get(),
		shell = c.setShell("System");
	c.run(shell, command);
}//}}}


//------------------------------------------------------------------------------
//DIALOGS


function alert(message) {//-{{{
	Macros.message(view, message);
}//}}}


function prompt(question, defaultValue) {//-{{{
	return Macros.input(view, question, defaultValue || '');
}//}}}


function confirm(question) {//-{{{
	var op = javax.swing.JOptionPane;
	return Macros.confirm(view, question, op.OK_CANCEL_OPTION) == op.OK_OPTION;
}//}}}


/**
 * Opens a file dialog box
 * @param curDir current directory [optional]
 * @return a list of absolute paths of files selected
 */
function openFileDialog(curDir) {//-{{{
	var i,
		files,
		self = openFileDialog
		dialog = self.dialog;

	if (dialog === null) {
		self.dialog = dialog = jedit.browser.VFSFileChooserDialog(view, '', 0, true, false)
	}
	dialog.setVisible(true)
	files = dialog.getBrowser().getSelectedFiles()

	paths = []
	for (var i = 0; i < files.length; i++) {
			paths[i] = files[i].getPath();
	}
	dialog.setVisible(false)
	return paths;
}
openFileDialog.dialog = null;
//}}}


//------------------------------------------------------------------------------
//WRAPPERS

var document = {
	write: function(text) {
		textArea.setSelectedText(text);
	},
	close: function() {
		jEdit.closeBuffer(view, buffer);
	},
	open: function(path){
		window.open(path);
	}
}

var window = {
	close: function() {
		jEdit.closeView(view);
	},
	open: function(path) {
		if (!path) {
			return jEdit.newFile(view);//returns buffer
		}
		jEdit.openFile(view, path);
	}
}

//unfortunately "console" will be used by the console plugin
var jsConsole = {

	//open the dock
	open: function(){
		view.getDockableWindowManager().addDockableWindow("console");
	},
	
	//returns the current console instance
	get: function(){
		var ConsolePlugin = jEdit.getPlugin("console.ConsolePlugin");
		return ConsolePlugin.getConsole(view);
	},

	print: function(destination, color, message){
		jsConsole.open();
		
		//get active sconsole
		var cInsta = jsConsole.get();
		
		//setup colors
		if (!jsConsole.colors) {
			jsConsole.colors = {
				plain: cInsta.getPlainColor(),
				warn: cInsta.getWarningColor(),
				error: cInsta.getErrorColor()
			}
		}
		
		//set shell (System / BeanShell / JavaScript)
		cInsta.setShell(destination);
		var output = cInsta.getOutput();
		output.print(jsConsole.colors[color], message);
	},

	log: function(message){
		jsConsole.print("System", "plain", message);
	},
	
	warn: function(message){
		jsConsole.print("System", "warn", message);
	},
	
	error: function(message){
		jsConsole.print("System", "error", message);
	}

}


//some caret functions (of the current textArea)
var caret = {
	position: function(to) {
		if (!to) return textArea.getCaretPosition();
		textArea.moveCaretPosition(to);
	},
	line: function(to) {
		//todo setter
		return textArea.getCaretLine();
	},
	center: function() {
		textArea.centerCaret();
	},
	toPrevChar: function() {
		textArea.goToPrevCharacter(false);
	},
	toNextChar: function() {
		textArea.goToNextCharacter(false);
	}
}

//textArea utilities
var textarea = {
	setSelectionRange: function(from, to, additive) {
		if (!to) to = from + 1;
		var action = additive ? "addToSelection" : "setSelection";
		textArea[action](new org.gjt.sp.jedit.textarea.Selection.Range(from, to));
	},
	
	expandSelectionToLines: function() {
		var selections = textArea.getSelection(),
			i, sel, origpos;
		
		//works with multiple selections
		for (i = 0; i < selections.length; i++) {
			sel = selections[i];
			origpos = textArea.getCaretPosition();
			textArea.moveCaretPosition(sel.getEnd());
			textArea.goToEndOfLine(true);
			textArea.moveCaretPosition(sel.getStart());
			textArea.goToStartOfLine(true);
			textArea.moveCaretPosition(origpos);
		}
	},
	
	getText: function(from, offset) {
		if (arguments.length == 0) {
			from = textArea.getCaretPosition();
			offset = 1;
		}
		if (offset < 0) {
			from += offset;
			offset = offset * -1;
		}
		return String(textArea.getText(from < 0 ? 0 : from, offset));
	}
}