package vs;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/doc/*")
public class DocDeliveryServlet extends HttpServlet {
	/**
	 *
	 */
	private static final long serialVersionUID = 203911783064136439L;

	// alternatively use jakarta.servlet.Filter
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pdfName = req.getPathInfo();
		if ((pdfName == null) || "".equals(pdfName)) {
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
		} else {
			try {
				Calendar now = Calendar.getInstance();
				if ((now.get(Calendar.HOUR_OF_DAY) > 6) && (now.get(Calendar.HOUR_OF_DAY) < 21)) {
					// Access only allowed between 06:00-21:00 (local time of server);
					// works here as a filter
					resp.sendError(HttpServletResponse.SC_FORBIDDEN,
							"access to " + pdfName + " is currently forbidden");
				} else {
					// => [ServletContext]/WebContent/doc/....pdf
					String pdfFilePath = getServletContext().getRealPath("/doc/" + pdfName);
					File pdfFile = new File(pdfFilePath);
					if (!pdfFile.exists()) {
						throw new Exception("file does not exist in doc/");
					}
					if (!pdfFile.isFile()) {
						throw new Exception("file ist not regular");
					}
					if (!pdfFile.canRead()) {
						throw new Exception("file not readable");
					}
					if (!pdfFile.getParentFile().getCanonicalPath()
							.equals((new File(getServletContext().getRealPath("/doc/"))).getCanonicalPath())) {
						throw new Exception("file not in doc/");
					}
					OutputStream out = resp.getOutputStream();
					resp.setHeader("Content-Disposition", "inline;filename=" + pdfName + "\"");
					resp.setContentType("application/pdf");
					try (InputStream in = new BufferedInputStream(new FileInputStream(pdfFile))) {
						int character;
						while ((character = in.read()) != -1) {
							out.write((byte) character);
						}
					} catch (Exception ex) {
						// an IOException could occur but can't be handled, at least in will be closed
					}
				}
			} catch (Exception e) {
				resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getLocalizedMessage());
			}

		}
	}

}
