package org.yacos.web.PCmember.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;
import org.yacos.core.article.Article;
import org.yacos.core.article.IArticleManager;
import org.yacos.core.article.Article.State;
import org.yacos.core.evaluation.IEvaluationManager;
import org.yacos.core.evaluation.Rating;
import org.yacos.core.evaluation.Report;
import org.yacos.web.system.session.SessionService;

public class EvaluationRemoveController implements Controller {
	private IArticleManager articleManager;
	private IEvaluationManager evaluationManager;

	public IArticleManager getArticleManager() {
		return articleManager;
	}

	public void setArticleManager(IArticleManager articleManager) {
		this.articleManager = articleManager;
	}

	public IEvaluationManager getEvaluationManager() {
		return evaluationManager;
	}

	public void setEvaluationManager(IEvaluationManager evaluationManager) {
		this.evaluationManager = evaluationManager;
	}

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		try {
			Integer articleId = Integer.parseInt(request.getParameter("articleId"));
			Article article = articleManager.getArticle(articleId);

			// FIXME : v�rifier si le gars a le droit de suppr ou pas

			if(article == null){
				return new ModelAndView(new RedirectView("404error.htm"));
			}

			Report rpt = evaluationManager.getReportforArticleAndReferee(article.getId(), SessionService.getInstance().getCurrentUserLogin());
			
			if (rpt == null)
				throw new ModelAndViewDefiningException(new ModelAndView("404error"));
			
			List<Report> listReport = evaluationManager.getReportsForArticle(article.getId());
			if (listReport.size() <= 1) {
				article.setState(State.SUBMITED);
				articleManager.updateArticle(article);
			}
				
			List<Rating> listRating = evaluationManager.getRatingForReport(rpt.getId());
			
			for (Rating rt : listRating) {
				evaluationManager.removeRating(rt.getCriterion(), rpt);
			}
			
			evaluationManager.removeReport(rpt.getId());

		} 
		catch(NumberFormatException e) {
			throw new ModelAndViewDefiningException(new ModelAndView("404error"));
		}

		String addr = request.getHeader("REFERER");
		
		if (addr.toLowerCase().contains("role=pcmember"))
			return new ModelAndView(new RedirectView("listEvaluation.htm?role=pcmember"));
		else if (addr.toLowerCase().contains("role=referee"))
			return new ModelAndView(new RedirectView("listEvaluation.htm?role=referee"));
		else 
			throw new ModelAndViewDefiningException(new ModelAndView("denied"));
	}

}