package org.yacos.web.author.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.yacos.core.evaluation.IEvaluationManager;
import org.yacos.core.evaluation.Rating;
import org.yacos.core.evaluation.Report;
import org.yacos.web.system.controller.NoConferenceSelectedException;


public class ListReportAuthorController extends SimpleFormController {

	protected final Log logger = LogFactory.getLog(getClass());

	private IEvaluationManager evaluationManager;

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException, NoConferenceSelectedException {

		logger.info("Returning listReport view");

		List<Report> listReport;
		String reportId = request.getParameter("id");

		try {

			Integer id = new Integer(reportId);

			Map <String, Object> model = new HashMap<String, Object>();

			listReport = evaluationManager.getReportsForArticle(id);

			if (listReport.isEmpty()) {
				model.put("whereIcome", request.getHeader("REFERER"));
				model.put("listReport", null);
				return new ModelAndView("listReport", model);
			}

			model.put("listReport", listReport);

			List<List<Rating>> container = new ArrayList<List<Rating>>();

			for (int i=0; i<=listReport.size()-1;i++){
				List<Rating> ratings = evaluationManager.getRatingForReport(listReport.get(i).getId());
				container.add(ratings);
			}
			model.put("container", container);
			model.put("whereIcome", request.getHeader("REFERER"));

			return new ModelAndView("listReport", model);
		}

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

	public IEvaluationManager getEvaluationManager() {
		return evaluationManager;
	}

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