package de.snailshell.consensus.demo.actions;

import java.util.Collection;

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 AttributeViewAction 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" );

		OntologyManager manager = this.getOntologyManager();
		
		User user = this.getUser(request);
		
		Topic     t = manager.getQueryEngine().getTopicById( user, topicid );
		Attribute a = t.getAttribute( user, attrid );
		Rating    r = a.getRating( user );
		
		Collection history = null;

		String ratingstr;

		if ((r != null) && (this.getRatingManager() != null)) {
			ratingstr = this.getRatingManager().ratingValueToString( r.getValue() );
			history   = r.getHistory();
		}
		else {
			ratingstr = "";
		}

		((DynaActionForm)form).set( "topicid", t.getId() );
		((DynaActionForm)form).set( "attrid", a.getId() );
		((DynaActionForm)form).set( "attrvalue", a.getValue() );
		((DynaActionForm)form).set( "attrcomment", a.getComment() );
		((DynaActionForm)form).set( "attrrating", ratingstr );
		((DynaActionForm)form).set( "ratingcomment", "" );
		
		request.setAttribute( Constants.REQUEST_ATTR_TOPIC, t );
		request.setAttribute( Constants.REQUEST_ATTR_ATTRIBUTE, a );
		request.setAttribute( Constants.REQUEST_ATTR_RATING, r );
		request.setAttribute( Constants.REQUEST_ATTR_RATINGHISTORY, history );
		
		return mapping.findForward( Constants.MAPPING_SUCCESS );
	}
}
