package com.capgemini.reports.common;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;

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

import lombok.extern.slf4j.Slf4j;

/**
 * JSP Servlet for downloading file content from web GUI.
 */
@Slf4j
@WebServlet("/testServlet")
public class TestServlet extends HttpServlet {

    /** Default serial UID. **/
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(final HttpServletRequest aRequest, final HttpServletResponse aResponse) throws ServletException, IOException {

        log.info("GET RECEIVED");
        processParams(aRequest, aResponse);
    }

    @Override
    protected void doPost(final HttpServletRequest aRequest, final HttpServletResponse aResponse) throws ServletException, IOException {
        log.info("POST RECEIVED");

        processParams(aRequest, aResponse);
    }


    private void processParams(final HttpServletRequest aRequest, final HttpServletResponse aResponse) {

        Enumeration<String> attNameEnum = aRequest.getAttributeNames();
        while (attNameEnum.hasMoreElements()) {
            String currentAtt = attNameEnum.nextElement();
            log.info("\t - Att: " + currentAtt + "=" + aRequest.getAttribute(currentAtt));
        }

        Enumeration<String> headerEnum = aRequest.getHeaderNames();
        while (headerEnum.hasMoreElements()) {
            String currentHeader = headerEnum.nextElement();
            log.info("\t - Head: " + currentHeader + "=" + aRequest.getHeader(currentHeader));
        }

        Map<String, String[]> parameterMap = aRequest.getParameterMap();

        for (Entry<String, String[]> entry : parameterMap.entrySet()) {

            String[] currentParamArray = entry.getValue();
            if (currentParamArray.length == 1) {
                log.info(entry.getKey() + "=" + currentParamArray[0]);
            }
            else {
                for (int i = 0; i < currentParamArray.length; i++) {
                    log.info(entry.getKey() + "[" + i + "] =" + currentParamArray[i]);
                }
            }
        }

        try {
            aResponse.getWriter().write("FINISHED");
        }
        catch (IOException e) {
            log.error("Error", e);
        }
    }
}
