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.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.User;

/**
 * @author Thomas Much
 * @version 2006-06-14
 */
public class CreateTopicAction 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 topicname = ((DynaActionForm)form).getString("topicname");
		String typeid    = ((DynaActionForm)form).getString("typeid");
		
		OntologyManager om = this.getOntologyManager();
		
		User user = this.getUser(request);
		
		Topic type = null;
		
		if ((typeid != null) && (typeid.length() > 0)) {
			type = om.getQueryEngine().getTopicById( user, typeid );
		}		
		
		Topic t = om.createTopic( user, null, topicname, type );
		
		// TODO: wie wird auf Fehler (z.B. Topic-Name (ID?) bereits vergeben) reagiert?
		// TODO: wie dürfen Namen doppelt vergeben werden? Warnung mit Liste der gleichnamigen Topics?

		request.setAttribute( Constants.REQUEST_ATTR_TOPIC, t );

		ConsensusFoundationUtils.addLastVisitedTopic( request, t );

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