//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package kinosearch.webapp.servlets;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kinosearch.core.Tools;
import kinosearch.webapp.WebApp;
import kinosearch.webapp.template.TemplateProcessor;

public class TemplateServlet extends HttpServlet {
    private static final long serialVersionUID = 5334243553000329769L;
    private TemplateProcessor template;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.template = WebApp.getTemplateProcessor();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fileName = Tools.getFileFromURI(req.getRequestURI(), req.getContextPath());
        Path path = Paths.get(this.getServletContext().getRealPath("WEB-INF/simple_template" + fileName));
        if (Files.exists(path, new LinkOption[0])) {
            Map<String, Object> model = WebApp.getDefaultModel(this.getServletContext());
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");

            try {
                this.template.process("simple_template" + fileName, model, resp.getWriter());
            } catch (IOException e) {
                this.log("Error process template", e);
                resp.sendError(500);
            }
        } else {
            resp.sendError(404);
            resp.setContentType("text/plain");
            resp.getWriter().write("404: not found");
        }

    }

    public void log(String message, Throwable t) {
        super.log(message, t);
    }
}
