package web.action;

import java.util.ArrayList;
import java.util.List;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import persistence.dao.DAOFactory;
import persistence.model.Usuario;
import util.exception.ServiceException;
import util.forward.StrutsForward;
import web.service.NoticiaService;
import web.service.NoticiaServiceImpl;
import web.service.UsuarioService;

public class LoginAction extends Action {

	private static final long serialVersionUID = 5184319597780160246L;
	private List<String> errors;
	private Usuario usuario;
	private NoticiaService noticiaService;
	private UsuarioService usuarioService;
    
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    		HttpServletRequest request, HttpServletResponse response)
    throws Exception {
    	String forward = StrutsForward.EXCEPTION;
		String login = request.getParameter("textLogin");
		String senha = request.getParameter("textPassword");
		
		try {
			noticiaService = DAOFactory.getInstance().getDao(NoticiaService.class);
			usuarioService = DAOFactory.getInstance().getDao(UsuarioService.class);
			
			errors = new ArrayList<String>();
			validaUsuario(login, senha);

			if ( errors.size() == 0 ) {
				noticiaService = new NoticiaServiceImpl();
				request.setAttribute("noticias", noticiaService.getAllNoticias());
				request.getSession().setAttribute("Usuario", usuario);

				forward = StrutsForward.SUCCESS;
			}
			else {
				request.setAttribute("errors", errors);
				forward = StrutsForward.ERROR;
			}
		}
		catch (Exception e) {
			request.setAttribute("exception", new ServiceException(e));
		}
		
		return mapping.findForward(forward);
	}
    
	private void validaUsuario(String login, String senha) {				
		if ("".equals(login)) {
			errors.add("Login vazio.");
		}	
		if ("".equals(senha)) {
			errors.add("Senha vazia.");
		}
		
		usuario = usuarioService.findByLoginAndSenha(login, senha);
		if (usuario == null && errors.size() == 0) {
			errors.add("Usuário ou senha inválido.");
		}
	}
}
