package de.snailshell.consensus.demo.actions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

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 de.snailshell.consensus.demo.ConsensusFoundationUtils;
import de.snailshell.consensus.demo.Constants;
import de.uka.ipd.consensus.foundation.ontology.OntologyManager;
import de.uka.ipd.consensus.foundation.rating.RatingManager;
import de.uka.ipd.consensus.foundation.schema.Rating;
import de.uka.ipd.consensus.foundation.schema.Synonym;
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 EditSynonymsAction extends BasisAction {

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

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

		OntologyManager om = this.getOntologyManager();

		User user = this.getUser( request );
		
		String id = request.getParameter( "id" );

		Topic t = om.getQueryEngine().getTopicById( user, id );

		if (t == null) {
			t = (Topic)request.getAttribute( Constants.REQUEST_ATTR_TOPIC );
		}

		Collection synonyms = t.getSynonyms( user );
		
		RatingManager rm = this.getRatingManager();

		ArrayList ratings = new ArrayList();
		
		Iterator it = synonyms.iterator();
		
		while (it.hasNext()) {
			Synonym syn = (Synonym)it.next();
			
			String str = "";
			
			if (rm != null) {
				Rating r = syn.getRating( user );
				
				if (r != null) {
					str = rm.ratingValueToString( r.getValue() );
				}
			}
			
			ratings.add( str );
		}
		
		ArrayList topics  = new ArrayList();
		
		Collection lastVisited = ConsensusFoundationUtils.getLastVisitedTopics( request );
		
		it = lastVisited.iterator();

		while (it.hasNext()) {
			Topic vt = (Topic)it.next();

			if (!t.isSynonymous( vt )) {
				topics.add( vt );
			}
		}

		request.setAttribute( Constants.REQUEST_ATTR_TOPIC, t );
		request.setAttribute( Constants.REQUEST_ATTR_TOPICS, topics );
		request.setAttribute( Constants.REQUEST_ATTR_SYNONYMS, synonyms );
		request.setAttribute( Constants.REQUEST_ATTR_RATINGS, ratings );
		
		return mapping.findForward( Constants.MAPPING_SUCCESS );
	}
}
