/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.http.server;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import org.apache.commons.fileupload.FileItem;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.List;

public final class ServletUtil {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ServletUtil.class);

    /**
     * Returns <code>true</code> if the version provides in the request is equal or greater
     * than the given <code>lastModifiedDate</code>, indicating that the servlet should not
     * serve the request.
     *
     * @param request
     * @param lastModifiedDate
     * @return
     */
    public static boolean isCached(final HttpServletRequest request, final long lastModifiedDate) {
        return (lastModifiedDate / 1000 * 1000) <=
                request.getDateHeader("If-Modified-Since");
    }

    /**
     * Write a standard-formatted HTTP error out to the response, and close the output stream.
     *
     * @param response
     * @param httpCode
     * @param msg
     * @throws IOException
     */
    public static void writeError(final HttpServletResponse response, final int httpCode, final String msg) throws IOException {

        response.setContentType("text/plain");
        response.setStatus(httpCode);
        final OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
        writer.write("ERROR: ");
        writer.write(msg);
        writer.write("\n");
        writer.close();
    }

    public static void printRequest(final HttpServletRequest request) {
        logger.info("Request: {}", request.getMethod());

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            logger.info("Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
        }

        Enumeration params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String paramName = (String) params.nextElement();
            logger.info("Parameter Name - " + paramName + ", Value - " + request.getParameter(paramName));
        }

    }

    public static FileItem getItemByName(final List<FileItem> items, String name) {
        for (FileItem item : items) {
            if (item.getFieldName().equals(name)) return item;
        }
        return null;
    }
}
