package it.micegroup.voila2.cartridge.library.formatters;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

public class SimpleXmlFormatterPostProcessor {
	public String format(String input) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		String[] lines = input.trim().split("\n");
		int lastIndent = 0;
		try {
			for (int i = 0; i < lines.length; i++) {
				if (!lines[i].trim().equals("")) {
					lastIndent = writeLine(baos, lines[i], lastIndent);
					baos.write("\n".getBytes());
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return baos.toString();
	}

	private int writeLine(ByteArrayOutputStream baos, String line, int lastIndent)
			throws IOException {
		line = convertSpacesToTabs(line);
		if (line.trim().startsWith("<")) {
			int pos = line.indexOf("<");
			int newpos = pos;
			if (pos > lastIndent) {
				newpos = lastIndent + 1;
				line = StringUtils.repeat("\t", newpos) + line.trim();
				lastIndent = newpos;
			}
		}
		baos.write(line.getBytes());
		return lastIndent;
	}

	private String convertSpacesToTabs(String line) {
		while (line.startsWith("    ")) {
			line = "\t" + line.substring(4);
		}
		return line;
	}
}
