/**
 * Updates the number of characters in the setext "underline"
 */

var setextSelector = new SXSelector('punctuation.setext');

action.canPerformWithContext = function(context, outError) {
	// Only possible if this line or the next is the underline
	var location = context.selectedRanges[0].location,
		zone = context.syntaxTree.zoneAtCharacterIndex(context.lineStorage.lineRangeForIndex(location).location),
		nextLineZone = context.syntaxTree.zoneAtCharacterIndex(context.lineStorage.lineStartIndexGreaterThanIndex(location));
	return setextSelector.matches(zone) || setextSelector.matches(nextLineZone);
};

action.performWithContext = function(context, outError) {
	// Determine our text line range and setext line range
	var location = context.selectedRanges[0].location,
		zone = context.syntaxTree.zoneAtCharacterIndex(context.lineStorage.lineRangeForIndex(location).location),
		nextLineZone = context.syntaxTree.zoneAtCharacterIndex(context.lineStorage.lineStartIndexGreaterThanIndex(location)),
		// Variables we'll use later
		recipe = new CETextRecipe(),
		textRange, setextRange;
	if (setextSelector.matches(nextLineZone)) {
		// Cursor is on the text line
		textRange = context.lineStorage.lineRangeForIndex(location);
		setextRange = nextLineZone.range;
	} else {
		// Cursor is on the setext line
		textRange = context.lineStorage.lineRangeForIndex(context.lineStorage.lineRangeForIndex(location).location - 1);
		setextRange = zone.range;
	}
	// Determine the length of the text, and the repeating character
	var numChars = context.substringWithRange(textRange).replace(/^(.+?)\s*$/, '$1').length,
		character = context.substringWithRange(new Range(setextRange.location, 1));
	recipe.replaceRange(setextRange, Array(numChars + 1).join(character));
	return context.applyTextRecipe(recipe);
};
