/*
 * $Id: WorkflowUtils.java,v 1.8 2006/10/04 03:15:20 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * Created on 14.07.2004
 *
 * $Log: WorkflowUtils.java,v $
 * Revision 1.8  2006/10/04 03:15:20  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.7  2006/03/06 15:11:58  jonyp
 * + Bugfix (wg. Oracle)
 *
 * Revision 1.6  2005/12/15 15:28:52  marbobo
 * + Benutzername und Passwort für Mailserver implementiert
 *
 * Revision 1.5  2005/01/20 15:25:52  marbobo
 * + Anpassungen an den Methoden getRootURL() und getContextName()
 *
 * Revision 1.4  2004/11/10 15:02:54  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.3  2004/11/09 16:08:02  marbobo
 * - Unnötige Anweisungen entfernt
 *
 * Revision 1.2  2004/09/20 10:26:12  koppy
 * +javadoc Dokumentation
 *
 * Revision 1.1  2004/08/30 14:50:00  koppy
 * Initiale Version der Workflow-Komponente
 *
 */
package vkc.workflow.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.velocity.runtime.RuntimeConstants;

import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCSysParameterSerializer;
import vkc.misc.MailUtils;
import vkc.misc.TemplateParser;
import vkc.misc.VKCLogManager;
import vkc.view.WebShare;
import vkc.workflow.WfConstants;
import vkc.workflow.WorkflowException;
import vkc.workflow.model.WorkItemInfo;

/**
 * This utility class provides
 * some useful methods for the workflow component.
 * 
 * @author Andreas Koop
 */
public final class WorkflowUtils {
    private static MailUtils mailer = new MailUtils(null);
    
    
    /**
     * Logs the stack trace and puts the exception message
     * in the request scope
     * 
     * @param request thte http request
     * @param e the workflow exception
     */
    public static final void handle( HttpServletRequest request, WorkflowException e ) {
        
        VKCLogManager.errorLog(WorkflowUtils.class, "", e.getMessage(),e);
        String message = e.getMessage();
        
        if (message.startsWith("wf.error")) {

            ActionErrors errors = new ActionErrors();
            errors.add( "workflow.error", new ActionError( message ) );
            request.setAttribute( WfConstants.ERROR_KEY, errors );
        }
    }
    
    /**
     * Adds a message to the http request
     * under the given message key.
     * 
     * @param request http request
     * @param messageKey message key
     */
    public static final void addMessage( HttpServletRequest request, String messageKey ) {
        WorkflowUtils.addMessage( request, new ActionMessage( messageKey ));
    }
    
    /**
     * Adds a message to the http request.
     * 
     * @param request htpp request
     * @param message the message to add 
     */
    public static final void addMessage( HttpServletRequest request, ActionMessage message ) {
        ActionMessages messages = (ActionMessages)request.getAttribute( WfConstants.MESSAGE_KEY );
        
        if ( messages == null ) {
            messages = new ActionMessages();
            request.setAttribute( WfConstants.MESSAGE_KEY, messages );
        }
        
        messages.add( message.getKey(), message );
    }
    
    /**
     * Checks whether a collection is empty or not.
     * 
     * @param c a collection
     * @return true if points to null or is empty, otherwise false.
     */
    public static final boolean isEmpty( Collection c ) {
        return c == null || c.isEmpty();
    }
    
    
    /**
     * Sends an Email to the given list of VKC-users about the
     * assignment for an outstanding workitem.
     * 
     * @param users List of users (type VKCUser)
     * @param workitem a workitem
     * @throws Exception
     */
    public static final void sendMail( List users, WorkItemInfo workitem ) throws Exception {
        if ( isEmpty( users ) ) {
            return;
        }
        
        Properties velocityProps = new Properties();
        velocityProps.setProperty( RuntimeConstants.RUNTIME_LOG, "logs/velocity.log" );
        velocityProps.setProperty( RuntimeConstants.RESOURCE_LOADER, "classpath" );
        velocityProps.setProperty( "classpath." + RuntimeConstants.RESOURCE_LOADER + ".class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" );
        TemplateParser parser = TemplateParser.getTemplateParser( velocityProps );
        
        String senderAddr  = VKCSysParameterSerializer.retrieveValue( "MAIL", "AdminEmail", "" );
		String smtpServer  = VKCSysParameterSerializer.retrieveValue( "MAIL", "MailServer", "" );
		String smtpUsername  = VKCSysParameterSerializer.retrieveValue( "MAIL", "MailUsername", "" );
		String smtpPassword  = VKCSysParameterSerializer.retrieveValue( "MAIL", "MailPassword", "" );
		String vkc_rootURL = WebShare.getRootURL() + WebShare.getContextPath();
		
		parser.setContextData( "workflow", workitem.getContainer().getName() );
		parser.setContextData( "workitem", workitem.getName() );
		parser.setContextData( "homepage", vkc_rootURL );
		
		for ( Iterator iter = users.iterator(); iter.hasNext(); ) {
            VKCUser user = (VKCUser) iter.next();
            
			// Put context data
			parser.setContextData( "firstname", user.getFirstname() );
			parser.setContextData( "lastname", user.getLastname() );
			
			String message = parser.createString( "vkc/workflow/mail/new_workitem_" + user.getLanguage().getShortName() + ".plain" );
			
			mailer.setUser(user);
            mailer.sendSMTPMail( senderAddr,
                    			 user.getEmail(),
                    			 "VKC-Workflow: " + workitem.getName(),
                    			 message,
                    			 null, 
                    			 null, 
                    			 null, 
                    			 smtpServer,
                    			 smtpUsername,
                    			 smtpPassword );
		}	
    }
}