package commands;

import java.io.IOException;

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

import business.Professor;
import business.Usuario;
import dao.FacadeDAO;
import dao.UsuarioDAO;

public class ProfessorAssociar extends AbstractCommand {

	private UsuarioDAO usuarioDao = null;

	@Override
	public void processarComando(HttpServletRequest request,
			HttpServletResponse response, HttpServlet servlet) throws IOException,
			ServletException {
		// Recupera os Parâmetros
		String idProfessorStr = request.getParameter("idProfessor");
		String idUsuarioStr = request.getParameter("idUsuario");

		if (idProfessorStr == null) {
			response
					.sendRedirect("Command?comando=ProfessorPrepararAssociar&msg=Nao ha professores cadastrados.");
			return;
		}

		if (idUsuarioStr == null) {
			response
					.sendRedirect("Command?comando=ProfessorPrepararAssociar&msg=Nao ha usuarios disponiveis.");
			return;
		}

		int idProfessor = Integer.parseInt(idProfessorStr);
		int idUsuario = Integer.parseInt(idUsuarioStr);

		// Cria um professor com os Parâmetros
		Professor professor = new Professor();
		professor.setId(idProfessor);

		// Cria um usuario com os Parâmetros
		Usuario usuario = new Usuario();
		usuario.setId(idUsuario);

		usuarioDao = FacadeDAO.getInstance(servlet).getUsuarioDAO();

		// Associa o professor ao usuário no Banco
		try {
			usuarioDao.associar(usuario, professor);
			response
					.sendRedirect("professorPrepararAssociar.jsp?msg=Professor associado.");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response
					.sendRedirect("Command?comando=ProfessorPrepararAssociar&msg="
							+ e.getMessage() + ".");
		}
	}
}
