package com.heckmansoft.surjey.controller;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.heckmansoft.surjey.controller.action.Action;
import com.heckmansoft.surjey.controller.action.ActionFactory;

/**
 * The Controller for the application.
 * Based upon the Front Controller pattern.
 */
public class Controller extends HttpServlet {

    private Logger log = Logger.getLogger(Controller.class);

    private ActionFactory actionFactory;

    /**
     * @see javax.servlet.http.HttpServlet#init(javax.servlet.ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        actionFactory = ActionFactory.newInstance(config);
    }

    /**
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException
    {
        log.debug("doGet()");

        // Lookup action name
        String actionName = (String) request.getAttribute("action");

        // Create instance of action
        Action action = actionFactory.newAction(actionName);

        // Verify action was created
        if (action == null) {
            throw new ServletException(
                "Unable to create action: " + actionName);
        }

        // Execute action, returning view name
        String viewName;
        try {
            viewName = action.execute(request, response);
        } catch (Exception e) {
            throw new ServletException(e);
        }

        // Lookup dispatcher for view name
        RequestDispatcher viewDispatcher = getServletContext().
            getNamedDispatcher(viewName);

        // Verify view dispatcher was found
        if (viewDispatcher == null) {
            throw new ServletException(
                "Unable to find view: " + viewName);
        }

        // Include view
        viewDispatcher.forward(request, response);

    }

    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException
    {
        this.doGet(request, response);
    }


}
