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.Assunto;
import persistence.model.Noticia;
import persistence.model.Usuario;
import util.exception.ServiceException;
import util.forward.StrutsForward;
import web.service.AssuntoService;
import web.service.NoticiaService;

public class AdicionaNoticiaAction extends Action {

	private static final long serialVersionUID = 5184319597780160246L;
	private List<String> errors;  
	private NoticiaService noticiaService;
	private AssuntoService assuntoService;
    
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    		HttpServletRequest request, HttpServletResponse response)
    throws Exception {
    	String forward = StrutsForward.EXCEPTION;
		String titulo = request.getParameter("textTitulo");
		String texto = request.getParameter("textTexto");
		Long assuntoId = Long.parseLong(request.getParameter("assuntoId"));
		Usuario usuario = null;

		try {
			noticiaService = DAOFactory.getInstance().getDao(NoticiaService.class);
			assuntoService = DAOFactory.getInstance().getDao(AssuntoService.class);
			errors = new ArrayList<String>();
			validaUsuario(titulo, texto);

			if ( errors.size() == 0 ) {
				usuario = (Usuario) request.getSession().getAttribute("Usuario");
				
				if (usuario != null) {
					Assunto assunto = assuntoService.findByID(assuntoId);
					Noticia noticia = new Noticia(usuario, assunto, titulo, texto);
					noticiaService.addNoticia(noticia);
					forward = StrutsForward.SUCCESS;
				}
				else {
					errors.add("Usuário não autenticado");
					request.setAttribute("errors", errors);
					forward = StrutsForward.NO_AUTHENTICATION;
				}
			}
			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 titulo, String texto) {				
		if ("".equals(titulo)) {
			errors.add("Título vazio.");
		}	
		if ("".equals(texto)) {
			errors.add("Texto vazio.");
		}
	}
}
