/*
 * $Id: ProcessDefinitionsAction.java,v 1.3 2005/07/26 23:05:46 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * Created on 13.07.2004
 *
 * $Log: ProcessDefinitionsAction.java,v $
 * Revision 1.3  2005/07/26 23:05:46  marbobo
 * + Alle bekannte Probleme mit IE behoben
 *
 * Revision 1.2  2004/09/20 10:26:13  koppy
 * +javadoc Dokumentation
 *
 * Revision 1.1  2004/08/30 14:49:57  koppy
 * Initiale Version der Workflow-Komponente
 *
 */
package vkc.workflow.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import vkc.db.entities.VKCUser;
import vkc.util.ServletUtils;
import vkc.workflow.WorkflowException;
import vkc.workflow.WorkflowServiceFactory;
import vkc.workflow.model.MappingInfo;
import vkc.workflow.service.VKCWorkflowService;
import vkc.workflow.service.WfMConnection;
import vkc.workflow.util.WorkflowUtils;

/**
 * This class represents a struts action for 
 * the following workflow operations:
 * <ul>
 * <li>process instantiation</li>
 * <li>participant mapping</li>
 * <li>unloading/closing a workflow package</li>
 * <li>Enabling/Disabling workflow definitions</li>
 * </ul>
 * @author Andreas Koop
 */
public class ProcessDefinitionsAction extends Action {
    /** 
     * (non-Javadoc)
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public ActionForward execute(ActionMapping mapping, ActionForm f,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        ProcessDefinitionsForm 	form	= (ProcessDefinitionsForm)f;
        VKCUser 				user 	= ServletUtils.getUser( request );
        VKCWorkflowService wfService 	= WorkflowServiceFactory.getWorkflowService();
        WfMConnection 			sConn	= new WfMConnection(
                							user.getUser(), user.getClearPassword());
        
        String action = form.getAction();
        String pkgId  = form.getPkgId();
        String procDefId = form.getProcDefId();
        String pMgrName  = request.getParameter( "pMgrName" );

        try {
            if( "partMapping.save".equals( action )){
                wfService.getUserMappingManager()
            		.setUserMappings( sConn, trimMappings( form.getPartMappings()) );
                WorkflowUtils.addMessage( request, "wf.message.partMapping_saved");
                
            }else if( "instantiateProcess".equals( action ) ){
                String procId = wfService.getProcessManager()
                .instantiateProcess( user,pkgId,procDefId);
                
                List context = wfService.getProcessManager()
                	.getContextVariables( sConn, user.getLanguage().getLocale(), procId, true);
                if( context.isEmpty()){
                    wfService.getProcessManager()
       					.startProcess( user, procId );
                    return new ActionForward( "/instances.do?detailId=" + 
                            procId + "&anchor=" + procId, true);
                }
                
                return new ActionForward( "/instances.do?initVariables=true&detailId=" + 
                        procId + "&anchor=" + procId, true);
                
            } else if ( "closePackage".equals( action ) ){
                wfService.getPackageManager().closePackage(sConn, pkgId);
            } else if ( "enable".equals( action )){
                setEnabled( wfService, sConn, pkgId, pMgrName, true);
            } else if ( "disable".equals( action )){
                setEnabled( wfService, sConn, pkgId, pMgrName, false);
            }
            
        } catch (WorkflowException e) {
            WorkflowUtils.handle( request, e);
        }
        
        return mapping.getInputForward();
    }


    /**
     * Trims the given mappings until
     * the participant id is set to null
     * and returns the mapping infos as array.
     * 
     * @param partMappings array of mapping infos
     * @return list of the trimmed mappings.
     */
    private List trimMappings(MappingInfo[] partMappings) {
        List l = new ArrayList();
        for (int i = 0; i < partMappings.length; i++) {
            MappingInfo info = partMappings[i];
            if(info.getParticipantId() == null)
                break;
            l.add(info);
        }
        
        return l;
    }


    /**
     * Enables/Disables whole package or a process definition.
     * 
     * @param wfService the workflow service
     * @param conn workflow connection
     * @param pkgId package id, can be null.
     * @param mgrName manager name, can be null.
     * @param b set to true to enable, otherwise to disable 
     */
    private void setEnabled(VKCWorkflowService wfService, WfMConnection sConn, String pkgId, String pMgrName, boolean b) 
    	throws WorkflowException{
        if( pMgrName != null){
            wfService.getPackageManager().setProcessDefinitionEnabled(
                    sConn, pMgrName, b);
        }
        
        if( pkgId != null ){
            wfService.getPackageManager().setPackageEnabled(
                    sConn, pkgId, b);
        }
        
    }

}
