package hiro.yoshioka.util;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LinesString {
	String[] lines;
	int[] offsets;

	public LinesString(String target) {
		Pattern PATTERN_CRLF = Pattern.compile("(\r\n|[\r\n])");
		Matcher m = PATTERN_CRLF.matcher(target);
		int offset = 0;
		ArrayList<String> lineList = new ArrayList<String>();
		ArrayList<Integer> lineOffsetList = new ArrayList<Integer>();
		while (m.find()) {
			String line = target.substring(offset, m.start());
			lineList.add(line);
			lineOffsetList.add(offset);
			offset = m.end();
		}
		if (offset < target.length()) {
			String line = target.substring(offset);
			lineList.add(line);
			lineOffsetList.add(offset);
		}
		lines = lineList.toArray(new String[lineList.size()]);
		offsets = new int[lineOffsetList.size()];
		for (int i = 0; i < offsets.length; i++) {
			offsets[i] = lineOffsetList.get(i);
		}
	}

	public int getOffsetByRowColIndex(int row, int col) {
		return offsets[row] + col;
	}

	public int getOffsetByRowColNumber(int row, int col) {
		return offsets[row - 1] + col - 1;
	}

}
