package de.snailshell.consensus.demo.actions;

import java.util.Iterator;
import java.util.Set;

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.ConsensusFoundationUtils;
import de.snailshell.consensus.demo.Constants;
import de.uka.ipd.consensus.foundation.ontology.OntologyManager;
import de.uka.ipd.consensus.foundation.schema.Topic;
import de.uka.ipd.consensus.foundation.schema.TypeInstance;
import de.uka.ipd.consensus.foundation.schema.User;

/**
 * @author Thomas Much
 * @version 2006-06-14
 */
public class NewAssociationAction 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 id = request.getParameter( "id" );

		OntologyManager manager = this.getOntologyManager();
		
		User user = this.getUser(request);

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

		String topicRoleId;

		Iterator it = t.getTypes(user).iterator();

		if (it.hasNext()) {
			topicRoleId = ((TypeInstance)it.next()).getType().getId();
		}
		else {
			topicRoleId = "";
		}
		
		Set roletypes = ConsensusFoundationUtils.getParentTypes( user, t );

		((DynaActionForm)form).set( "topicid", id );
		((DynaActionForm)form).set( "topicroleid", topicRoleId );
		((DynaActionForm)form).set( "assocname", "" );
		((DynaActionForm)form).set( "assoctypeid", "" );

		request.setAttribute( Constants.REQUEST_ATTR_TOPIC, t );
		request.setAttribute( Constants.REQUEST_ATTR_ROLETYPES, roletypes );
		
		return mapping.findForward( Constants.MAPPING_SUCCESS );
	}
}
