package projet;

public class HtmlBlocRenderer implements BlocRenderer {

	@Override
	public String renderTexte(String contenu) {
		contenu = escapeHtml(contenu);
		return "<p>" + contenu + "</p>\n";
	}

	@Override
	public String renderListe(String contenu, String style) {
		contenu = escapeHtml(contenu);
		
		StringBuilder sb = new StringBuilder();
		String[] items = contenu.split("\n");
		String tag = "bullet".equals(style) ? "ul" : "ol";
		sb.append("<").append(tag).append(">\n");
		for (String item : items) {
			sb.append("  <li>").append(item).append("</li>\n");
		}
		sb.append("</").append(tag).append(">\n");
		return sb.toString();
	}

	@Override
	public String renderTitre(String contenu, int level) {
		contenu = escapeHtml(contenu);
		
		level = Math.max(1, Math.min(level, 6));
		return "<h" + level + ">" + contenu + "</h" + level + ">\n";
	}

	@Override
	public String renderCode(String contenu, String language) {
		contenu = escapeHtml(contenu);
		
		return "<pre><code class=\"" + language + "\">\n" + contenu + "\n</code></pre>\n";
	}

	@Override
	public String renderPage(String title, String from) {
		return "<a href=\"page:" + from + "\">" + title + "</a>\n";
	}

	@Override
	public String renderSeparateur() {
		return "<hr/>\n";
	}

	@Override
	public String renderCitation(String contenu, String type) {
		contenu = escapeHtml(contenu);
		
		return "<blockquote class=\"" + type + "\">\n" + contenu + "\n</blockquote>\n";
	}

	public static String escapeHtml(String content) {
		if (content == null) return null;
		
		content = content.replaceAll("\n", "<br />");
		content = content.replaceAll("\\*\\*(.*?)\\*\\*", "<b>$1</b>");
		content = content.replaceAll("\\*(.*?)\\*", "<i>$1</i>");
		content = content.replaceAll("`(.*?)`", "<code>$1</code>");

		return content;
	}

}
