
import java.util.logging.Logger;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import java.security.Principal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SearchServlet extends javax.servlet.http.HttpServlet
{
   private static final Logger         LOGGER   = Logger.getLogger("PSearch");
   private static final SearchSettings settings = SearchSettings.getInstance("search.properties");


   public void init() throws ServletException
   {
      super.init();

      LOGGER.info("DB   : " + settings.dbConn.toString());
   }

   protected void doMultiValuedParamNotSupported(String message, PrintWriter printWriter)
   {
      printWriter.println("MultiValuedParamNotSupported : " + message);
   }

   protected void doUsageError(String message, PrintWriter printWriter)
   {
      printWriter.println("UsageError : " + message);
   }

   protected void doError(String message, PrintWriter printWriter)
   {
      printWriter.println("Error : " + message);
   }


   protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, UnsupportedEncodingException
   {
      LOGGER.info("trace");
      legacyLogEntry(request);

      try
      {
         Map<String, String[]> params = request.getParameterMap();
         Coord                  coord = new Coord(params);
         SubsurveyId      subsurveyId = new SubsurveyId(params);

         /* query Obscore table */

         DbPSearch dbps;
         synchronized(DbPSearch.class)
         {
            dbps = new DbPSearch(settings.dbConn);
         }
         String[] pubdidArr = dbps.queryOverlapingPubdid(coord, subsurveyId);

         final String RESPONSE_ENCODING = "UTF-8";

         /* if filters installed response will be wrapped */

         if(response instanceof FormatResponseWrapper)
         {
            LOGGER.info("response-type is FormatResponseWrapper");

            response.setContentType("text/plain");
            response.setCharacterEncoding(RESPONSE_ENCODING);

            /* collect all search description and set to wrapped response */

            FormatResponseWrapper responseWrapper = (FormatResponseWrapper) response;
            responseWrapper.setPubdidArr(pubdidArr);
         }
         else
         {
            LOGGER.info("response-type is HttpServletResponse");

            response.setContentType("text/plain");
            response.setCharacterEncoding(RESPONSE_ENCODING);

            PrintWriter writer = response.getWriter();
            for(String pubdid : pubdidArr)
            {
               writer.println(pubdid);
            }
            writer.close();
         }
      }
      catch(MultiValuedParamNotSupported ex)
      {
         LOGGER.info("MultiValuedParamNotSupported: " + ex.getMessage());

         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
         response.setContentType("text/plain");

         PrintWriter writer = response.getWriter();
         doMultiValuedParamNotSupported(ex.getMessage(), writer);
         writer.close();
      }
      catch(IllegalArgumentException ex)
      {
         LOGGER.info("IllegalArgumentException: " + ex.getMessage());

         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
         response.setContentType("text/plain");

         PrintWriter writer = response.getWriter();
         doUsageError(ex.getMessage(), writer);
         writer.close();
      }
      catch(Exception ex)
      {
         LOGGER.info("Exception: " + ex.getMessage());
         ex.printStackTrace();

         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
         response.setContentType("text/plain");

         PrintWriter writer = response.getWriter();
         doError(ex.toString(), writer);
         writer.close();
      }

      return;
   }


   private void legacyLogEntry(HttpServletRequest request) throws UnsupportedEncodingException
   {
      StringBuffer requestURL = request.getRequestURL();
      if (request.getQueryString() != null)
      {
         requestURL.append("?").append(request.getQueryString());
         String completeURL = requestURL.toString();
         String className = this.getClass().getSimpleName();
         LOGGER.info(className + " vlkb req from: "
               + request.getRemoteAddr()
               + " doGet: " + URLDecoder.decode(completeURL, "UTF-8"));
      }
   }


}

