package br.com.senacagil.springmvc.commands;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

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

import br.com.senacagil.springmvc.business.Professor;
import br.com.senacagil.springmvc.business.Usuario;
import br.com.senacagil.springmvc.dao.FacadeDAO;
import br.com.senacagil.springmvc.dao.ProfessorDAO;
import br.com.senacagil.springmvc.dao.UsuarioDAO;

public class ProfessorPrepararAssociar extends AbstractCommand {

	private ProfessorDAO professorDao = null;
	private UsuarioDAO usuarioDao = null;

	@Override
	public void processarComando(HttpServletRequest request,
			HttpServletResponse response, HttpServlet servlet) throws IOException,
			ServletException {
		// Pede os Professores para o DAO
		professorDao = FacadeDAO.getInstance(servlet).getProfessorDAO();
		List<Professor> listaProfessores = professorDao.listarProfessores();

		// Guarda como atributo de requisição
		request.setAttribute("listaProfessores", listaProfessores);

		List<Usuario> listaUsuarios = null;
		usuarioDao = FacadeDAO.getInstance(servlet).getUsuarioDAO();
		try {
			listaUsuarios = usuarioDao.listarNaoAssociados();
			request.setAttribute("listaUsuarios", listaUsuarios);
			// Redireciona a requisição internamente para a página
			RequestDispatcher rd = request
					.getRequestDispatcher("professorPrepararAssociar.jsp");
			rd.forward(request, response);
		} catch (ClassNotFoundException e) {
			request.setAttribute("listaUsuarios", null);
			e.printStackTrace();
			RequestDispatcher rd = request
					.getRequestDispatcher("professorPrepararAssociar.jsp?msg="
							+ e.getMessage() + ".");
			rd.forward(request, response);
		} catch (SQLException e) {
			request.setAttribute("listaUsuarios", null);
			e.printStackTrace();
			RequestDispatcher rd = request
					.getRequestDispatcher("professorPrepararAssociar.jsp?msg="
							+ e.getMessage() + ".");
			rd.forward(request, response);
		}
	}
}
