package ctbrec.docs;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Objects;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.options.MutableDataSet;

public class MarkdownServlet extends AbstractDocServlet {

    private static final transient Logger LOG = LoggerFactory.getLogger(MarkdownServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getRequestURI();
        LOG.trace("Path: [{}]", path);
        try {
            if(Objects.equal(path, "/docs/index.md")) {
                listPages(resp);
            } else {
                String md = loadMarkdown(path);
                String html = markdownToHtml(md);
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().println(getHeader());
                resp.getWriter().println(html);
                resp.getWriter().println(getFooter());
            }
        } catch (FileNotFoundException e) {
            error(resp, HttpServletResponse.SC_NOT_FOUND, "");
        }
    }

    private void listPages(HttpServletResponse resp) throws IOException {
        List<String> pages = getPages();
        String html = "<ul>";
        for (String page : pages) {
            html += "<li><a href=\"/docs/" + page + "\">" + page + "</a></li>";
        }
        html += "</ul>";
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().println(getHeader());
        resp.getWriter().println(html);
        resp.getWriter().println(getFooter());
    }

    private String markdownToHtml(String markdown) {
        MutableDataSet options = new MutableDataSet();
        Parser parser = Parser.builder(options).build();
        HtmlRenderer renderer = HtmlRenderer.builder(options).build();
        Node document = parser.parse(markdown);
        String html = renderer.render(document);
        return html;
    }
}
