package de.snailshell.consensus.demo.actions;

import java.io.InputStream;
import java.util.ArrayList;

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 org.apache.struts.upload.FormFile;

import de.snailshell.consensus.demo.Constants;
import de.uka.ipd.consensus.foundation.ontology.ImportHandler;
import de.uka.ipd.consensus.foundation.ontology.OntologyManager;
import de.uka.ipd.consensus.impl.UserImpl;

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

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

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

		if (!((UserImpl)getUser(request)).isSuperAdmin()) {
			return mapping.findForward( Constants.MAPPING_FAILURE );			
		}

		FormFile formfile = (FormFile)((DynaActionForm)form).get("formfile");
		
		String filename = formfile.getFileName();

		OntologyManager om = this.getOntologyManager();
		
		ImportHandler handler = om.getMergeHandler( filename );
		
		ArrayList errors = new ArrayList();
		
		if (filename.length() == 0) {
			errors.add( new Exception("Dateiname fehlt") );
		}
		else if (handler == null) {
			errors.add( new Exception("Kein Import-Handler f&uuml;r \"" + filename + "\" vorhanden.") );
		}
		else {
			try {
				InputStream in = formfile.getInputStream();
				handler.mergeOntology( in, errors );
				// in will be closed by mergeOntology()
			}
			catch (Exception e) {
				errors.add( e );
			}
		}
		
		request.setAttribute( Constants.REQUEST_ATTR_ERRORS, errors );

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