/*
Inserts arbitrary text over all selections

action.setup:
	- snippet (string): the default text to insert
	- alternatives (dictionary): keys are selectors, values are text to insert
	- prefix (bool): if text should precede the selection
	- suffix (bool): if text should follow selected text
*/

var utils = loadLibrary('tea-utils');

action.performWithContext = function(context, outError) {
	// Require snippet
	if (!action.setup.snippet) {
		console.log("TEA error: insert_text requires <snippet>");
		return false;
	}
	// Grab our ranges
	var ranges = context.selectedRanges;
	// Setup our text recipe
	var insertions = new CETextRecipe();
	// Loop over our selections
	var count = ranges.length;
	var range, text;
	for (var i = 0; i < count; i++) {
		range = ranges[i];
		// Grab the selected text
		text = context.string.substringWithRange(range);
		if (text != '' && (action.setup.prefix || action.setup.suffix)) {
			if (action.setup.prefix) {
				text = '$INSERT' + text;
			}
			if (action.setup.suffix) {
				text += '$INSERT';
			}
		} else {
			text = '$INSERT';
		}
		// Check for zone-specific insertions
		var insert = action.setup.snippet;
		if (action.setup.alternatives) {
			insert = utils.selectFromZones(context, range, insert, action.setup.alternatives);
		}
		// Replace our custom variables
		text = text.replace('$INSERT', insert);
		text = text.replace('$TOUCH', '');
		// Insert the text, or replace the selected text
		if (range.length === 0) {
			insertions.insertAtIndex(range.location, text);
		} else {
			insertions.replaceRange(range, text);
		}
	}
	// Set the undo name, if one was passed
	if (action.setup.undoName) {
		insertions.undoActionName = action.setup.undoName;
	}
	
	var resetCursor = false;
	if (ranges.length === 1 && ranges[0].length === 0) {
		// Thanks to insertAtIndex's wonkiness, we have to reset the cursor
		resetCursor = true;
	}
	// Insert our text
	var returnVal = context.applyTextRecipe(insertions);
	// And reset the cursor if necessary
	if (resetCursor) {
		var newRange = new Range(ranges[0].location + text.length, 0);
		context.selectedRanges = [newRange];
	}
	return returnVal;
};