package br.dsc.upe.poli.mvc;

import java.io.IOException;

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

/**
 * Servlet implementation class ServletControlador
 */
public class ServletControlador extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletControlador() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	protected void service(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
	String business = request.getParameter("operacao");
	String className = "br.dsc.upe.poli.mvc." + business;
	
	try {
	Class clazz = Class.forName(className);
	if (!LogicaDeNegocio.class.isAssignableFrom(clazz)) {
		throw new ServletException("classe não implementa a interface: " + className);
		}
	
	LogicaDeNegocio logicaDeNegocio = (LogicaDeNegocio) clazz.newInstance();
	logicaDeNegocio.execute(request, response);
	} catch (ClassNotFoundException e) {
	throw new ServletException("Não encontro a classe " + className);
	} catch (InstantiationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		throw new ServletException (e);
	} catch (Exception e) {
		e.printStackTrace();
		throw new ServletException("A lógica de négocios causou uma exceção");
	}	
	}
	
	}
