package com.javahonk;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.HttpMethod;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class MessageHandler extends AbstractHandler {

	private static final Logger logger = LogManager.getLogger(MessageHandler.class.getName());
	private static String URL_OPTION_EXPIRY = "/app/javahonk/test";
	
	public void handle(String target, Request baseRequest,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		logger.info("HTTP remote box- " + request.getRemoteAddr());
		logger.info("HTTP request- " + request.getPathInfo());

		if (request.getMethod().equals(HttpMethod.POST)) {
			StringBuilder sb = new StringBuilder();
			BufferedReader bufferedReader = null;

			try {
				bufferedReader = request.getReader();
				char[] charBuffer = new char[128];
				int bytesRead;
				while ((bytesRead = bufferedReader.read(charBuffer)) != -1)
					sb.append(charBuffer, 0, bytesRead);

				if (request.getPathInfo().equals(URL_OPTION_EXPIRY)) {
					System.out.println("Post request value: -->"+sb.toString());					
				} else {
					logger.error("Unable to process request from URL [ {} ]" , request.getPathInfo());
				}

			} catch (Exception e) {
				logger.error("Error :", e);
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);				
			} finally {
				if (bufferedReader != null) {
					try {
						bufferedReader.close();
					} catch (IOException e) {
						logger.error("Error :", e);
						response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
					}
				}
			}

		}
		response.setStatus(HttpServletResponse.SC_OK);
		baseRequest.setHandled(true);
	}
}