package fr.umlv.poo.s6_b;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;


public class Xml1Generator {
	
	public static void process(Path markdown, Path html) throws IOException {
		try (BufferedWriter writer = Files.newBufferedWriter(html,
				Charset.forName("utf-8"))) {
			writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
			writer.write("<esipe-report>\n");
			Scanner scanner = new Scanner(markdown, "utf-8");
			String previousLine = null;
			int level = 0;
			while (scanner.hasNext()) {
				String line = scanner.nextLine();
				if (line.startsWith("=")) {
					// TOD: fail if level == 2
					if (level == 1) { writer.write("</section>\n"); level --; }
					writer.write("<section>\n<title>" + previousLine + "</title>\n");
					previousLine = "";
					level ++;
				} else if (line.startsWith("-")) {
					if (level == 2) { writer.write("</section>\n"); level --; }
					writer.write("<section>\n<title>" + previousLine + "</title>\n");
					previousLine = "";
					level ++;					
				} else if (line.isEmpty() && ! previousLine.isEmpty()) {
					writer.write("<text>" + previousLine + "</text>\n");
					previousLine = "";
				} else {
					previousLine = line;
				}				
			}
			scanner.close();
			
			// close opened sections
			if (level == 2) { writer.write("</section>\n"); level --; }
			if (level == 1) { writer.write("</section>\n"); level --; }
			
			writer.write("</esipe-report>\n");
		}
	}

	public static void main(String[] args) throws IOException {
		Path markdown = Paths.get("./resources/rapport.md");
		Path xml = Paths.get("./rapport.xml1");
		process(markdown, xml);
	}

}
