package ru.yandex.autodoc.wmtools.view;

import org.apache.commons.lang3.tuple.Pair;
import ru.yandex.autodoc.common.doc.view.Markup;
import ru.yandex.autodoc.common.doc.view.common.MarkupRequestHandler;
import ru.yandex.autodoc.common.doc.view.common.Renderer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author avhaliullin
 */
public class MarkupServlet extends HttpServlet {
    private final Renderer renderer;
    private final MarkupRequestHandler handler;

    public MarkupServlet(Renderer renderer, MarkupRequestHandler handler) {
        this.renderer = renderer;
        this.handler = handler;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(renderer.contentType());
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");

        Map<String, String> params = req.getParameterMap().entrySet().stream()
                .map(e -> Pair.of(e.getKey(), e.getValue()[0]))
                .collect(Collectors.toMap(Pair::getKey, Pair::getValue));

        Markup markup = handler.handle(params);
        String result = renderer.render(markup, params);
        ;
        resp.getWriter().print(result);
    }
}
