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

public class AdicionaAvaliacaoAction extends Action {

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

			if ( errors.size() == 0 ) {
				usuario = (Usuario) request.getSession().getAttribute("Usuario");
				
				if (usuario != null) {
					Noticia noticia = noticiaService.findByID(Long.parseLong(noticiaId));

					if (!avaliacaoService.avaliacaoExists(usuario.getIdUsuario(), noticia.getIdNoticia())) {
						Avaliacao avaliacao;

						if(avaliacaoUsuario.equals("positiva")) {					
							avaliacao = new Avaliacao(noticia, usuario, 1);
						}
						else {
							avaliacao = new Avaliacao(noticia, usuario, -1);
						}

						avaliacaoService.addAvaliacao(avaliacao);
						forward = StrutsForward.SUCCESS;
					}
					else {
						errors.add("Você já avaliou esta notícia.");
						request.setAttribute("errors", errors);
						forward = StrutsForward.ERROR;
					}
				}
				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 avaliacao) {				
		if (avaliacao == null) {
			errors.add("Avaliação não preenchida.");
		}	
	}
}
