package projet;

public class LatexBlocRenderer implements BlocRenderer {

    @Override
    public String renderTexte(String contenu) {
    	contenu = escapeLatex(contenu);
    	
        return contenu + "\n\n";
    }

    @Override
    public String renderListe(String contenu, String style) {
    	
        StringBuilder sb = new StringBuilder();
        String env = "bullet".equals(style) ? "itemize" : "enumerate";
        sb.append("\\begin{").append(env).append("}\n");
        for (String item : contenu.split("\n")) {
            sb.append("  \\item ").append(item).append("\n");
        }
        sb.append("\\end{").append(env).append("}\n\n");
        return sb.toString();
    }

    @Override
    public String renderTitre(String contenu, int level) {
    	contenu = escapeLatex(contenu);
    	
        switch (level) {
            case 1: return "\\section{" + contenu + "}\n\n";
            case 2: return "\\subsection{" + contenu + "}\n\n";
            case 3: return "\\subsubsection{" + contenu + "}\n\n";
            default: return "\\paragraph{" + contenu + "}\n\n";
        }
    }

    @Override
    public String renderCode(String contenu, String language) {
    	contenu = escapeLatex(contenu);
    	
        return "\\begin{verbatim}\n" + contenu + "\n\\end{verbatim}\n\n";
    }

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

    @Override
    public String renderSeparateur() {
        return "\\noindent\\rule{\\linewidth}{0.4pt}\n\n";
    }

    @Override
    public String renderCitation(String contenu, String type) {
    	contenu = escapeLatex(contenu);
    	
        return "\\begin{quote}\n" + contenu + "\n\\end{quote}\n\n";
    }
    
	public static String escapeLatex(String content) {
		if (content == null) return null;
		
		content = content.replaceAll("\n", "\\\\\\\\ \n");
		content = content.replaceAll("\\*\\*(.*?)\\*\\*", "\\\\textbf{$1}");
		content = content.replaceAll("\\*(.*?)\\*", "\\\\textit{$1}");
		content = content.replaceAll("`(.*?)`", "\\\\texttt{$1}");

		return content;
	}
}
