package de.snailshell.consensus.demo.actions;

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

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

import de.snailshell.consensus.demo.Constants;
import de.uka.ipd.consensus.foundation.ontology.OntologyManager;
import de.uka.ipd.consensus.foundation.schema.Attribute;
import de.uka.ipd.consensus.foundation.schema.Rating;
import de.uka.ipd.consensus.foundation.schema.Topic;
import de.uka.ipd.consensus.foundation.schema.User;

/**
 * @author Thomas Much
 * @version 2006-06-14
 */
public class ChangeAttributeRatingAction extends BasisAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		if (!isUserLoggedOn(request)) {
			return mapping.findForward( Constants.MAPPING_FAILURE );
		}

		String topicid   = request.getParameter("id");
		String attrid    = request.getParameter("attrid");
		String ratingstr = ((DynaActionForm)form).getString("attrrating");
		String comment   = ((DynaActionForm)form).getString("ratingcomment");
		
		double value;
		
		if (this.getRatingManager() != null) {
			value = this.getRatingManager().stringToRatingValue( ratingstr );
		}
		else {
			value = Rating.NEUTRAL;
		}

		OntologyManager om = this.getOntologyManager();
		
		User user = this.getUser(request);
		
 		Topic t = om.getQueryEngine().getTopicById( user, topicid );
 		
 		Attribute a = t.getAttribute( user, attrid );
		
		Rating r = a.addRating( user, value );

		r.setComment( user, comment );

		this.getLoggingManager().debug("Change rating for " + a + " to " + ratingstr + "/" + value + " (by " + user + ")");

		return mapping.findForward( Constants.MAPPING_SUCCESS );
	}
}
