package org.metaborg.sunshine.model.messages;

import java.util.Arrays;

public class CodeRegionHelper {

	public static final char DAMAGE = '^';
	public static final char BLANK = ' ';
	public static final char TAB = '\t';
	public static final char NEWLINE = '\n';

	public static String[] getAffectedLines(String input, int beginLine, int endLine) {
		if (input.length() > 0 && beginLine > 0 && endLine > 0)
			return Arrays.copyOfRange(input.split("\\r?\\n"), beginLine - 1, endLine);
		else
			return new String[0];
	}

	public static String[] weaveDamageLines(String[] lines, int beginColumn, int endColumn) {
		String[] damagedLines = new String[lines.length * 2];
		for (int i = 0; i < lines.length; i++) {
			String line = lines[i];
			damagedLines[i] = line;
			int beginOffset = i == 0 ? beginColumn - 1 : 0;
			int endOffset = i + 1 == lines.length ? endColumn - 1 : line.length();
			char[] damageChars = line.toCharArray();
			for (int j = 0; j < damageChars.length; j++) {
				if (beginOffset <= j && endOffset >= j) {
					damageChars[j] = DAMAGE;
				} else {
					char dc = damageChars[j];
					if (dc != TAB && dc != BLANK) {
						dc = BLANK;
					}
					damageChars[j] = dc;
				}
			}
			damagedLines[i + 1] = new String(damageChars);
		}
		return damagedLines;
	}
}

@@ -401,16 +401,131 @@
 ine %3E 0)
+ %7B%0A%09%09%09final String%5B%5D lines = input.split(%22%5C%5Cr?%5C%5Cn%22);%0A%09%09%09if (beginLine - 1 %3E lines.length)%0A%09%09%09%09return new String%5B0%5D;
 %0A%09%09%09retu
@@ -546,38 +546,21 @@
 OfRange(
+l
 in
-put.split(%22%5C%5Cr?%5C%5Cn%22)
+es
 , beginL
@@ -578,16 +578,20 @@
 dLine);%0A
+%09%09%7D%0A
 %09%09else%0A%09

Fix array copy crash when beginning line exceeds number of lines.