package edu.hawaii.ics415.problem2.tabulardata.control;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import edu.hawaii.ics415.problem2.tabulardata.util.DataContainer;

/**
 * The central servlet that serves as the controller in the MVC pattern for JSP
 * page dispatching.
 *
 * @author   Takuya Yamashita
 */

public class Controller extends HttpServlet {

  /**
   * Provides the DataContainer object which is instantiated once in the init()
   * method.
   */
  private DataContainer dataContainer;

  /**
   * Instantiate the servlet container.
   *
   * @param conf                  The servlet configuration information.
   * @exception ServletException  If errors occur during initialization.
   */
  public void init(ServletConfig conf) throws ServletException {
    super.init(conf);
    dataContainer = new DataContainer(getServletContext());
  }


  /**
   * @param request               The servlet request object.
   * @param response              The servlet response object.
   * @exception ServletException  If problems occur with the request or rsponse.
   * @exception IOException       If problems occur during request forwarding.
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
    String commandName = (String) request.getParameter("CommandName");
    String fileName = (String) request.getParameter("fileName");
    String delimiter = (String) request.getParameter("delimiter");

    RequestDispatcher dispatcher;

    request.setAttribute("tabularIterator", "");
    if (commandName != null && commandName.equals("Query")) {
      try {
        dataContainer.initDataContainer(fileName, delimiter);
      }
      catch (IOException e) {
        throw e;
      }
      request.setAttribute("tabularIterator", dataContainer.iterator());
    }
    dispatcher = getServletContext().getRequestDispatcher("/problem2.jsp");
    dispatcher.forward(request, response);
  }


  /**
   * Dispatches to doPost for processing.
   *
   * @param request               The servlet request.
   * @param response              The servlet response.
   * @exception ServletException  If problems during request/response
   *      processing.
   * @exception IOException       If problems during the forward to the JSP
   *      page.
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
    doPost(request, response);
  }
}