/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.jetspeed.modules.actions.portlets;

// Turbine stuff
import org.apache.turbine.util.Log;
import org.apache.turbine.util.RunData;

// Jetspeed stuff
import org.apache.jetspeed.portal.Portlet;
import org.apache.jetspeed.om.registry.Parameter;
import org.apache.jetspeed.services.Registry;
import org.apache.jetspeed.om.registry.PortletEntry;
import org.apache.jetspeed.services.resources.JetspeedResources;

// Java stuff
import java.util.Hashtable;
import java.util.Iterator;
import java.io.File;

import javax.mail.Session;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;

/**
 * This action sets up the template context for retrieving stock quotes.
 *
 * @author <a href="mailto:morciuch@apache.org">Mark Orciuch</a>
 * @author <a href="mailto:weaver@apache.org">Scott T. Weaver</a>
 * @version $Id: QuestionnaireAction.java,v 1.5 2003/03/24 01:07:09 weaver Exp $ 
 */

public class QuestionnaireAction extends JspPortletAction
{

    /**
     * Build the normal state content for this portlet.
     *
     * @param portlet The jsp-based portlet that is being built.
     * @param rundata The turbine rundata context for this request.
     */
    protected void buildNormalContext(Portlet portlet, RunData rundata)
    {
        PortletEntry entry = (PortletEntry) Registry.getEntry(Registry.PORTLET, portlet.getName());
        Iterator i = entry.getParameterNames();
        Hashtable qa = new Hashtable();

        while (i.hasNext())
        {
            String name = (String) i.next();
            Parameter param = entry.getParameter(name);
            if (param.isHidden() == false)
            {
                String title = param.getTitle();
                String value = portlet.getPortletConfig().getInitParameter(name);
                qa.put(title, value);
            }
        }

        rundata.getRequest().setAttribute("questions", qa);

        // After successful send, the user may or may not click the Continue button so
        // reset to default template here
        if (rundata.getRequest().getAttribute("email") == null)
        {
            //this.setTemplate(rundata, portlet, null);
            resetTemplate(rundata);
        }

    }

    /**
     * Continue event handler.
     *
     * @param portlet The jsp-based portlet that is being built.
     * @param rundata The turbine rundata context for this request.
     */
    public void doContinue(RunData rundata, Portlet portlet)
    {
        // this.setTemplate(rundata, portlet, null);
        resetTemplate(rundata);
    }

    /**
     * Sort the quotes.
     *
     * @param portlet The jsp-based portlet that is being built.
     * @param rundata The turbine rundata context for this request.
     */
    public void doEmail(RunData rundata, Portlet portlet)
    {
        StringBuffer emailBody = new StringBuffer();
        PortletEntry entry = (PortletEntry) Registry.getEntry(Registry.PORTLET, portlet.getName());
        Iterator i = entry.getParameterNames();

        while (i.hasNext())
        {
            String name = (String) i.next();
            Parameter param = entry.getParameter(name);
            if (param.isHidden() == false)
            {
                String title = param.getTitle();
                String value = portlet.getPortletConfig().getInitParameter(name);
                value = value == null || value.length() == 0 ? "NOT PROVIDED" : value;
                emailBody.append(title);
                emailBody.append(" ===> ");
                emailBody.append(value);
                emailBody.append("\n\n");

            }
        }

        String emailSmtp = JetspeedResources.getString(JetspeedResources.MAIL_SERVER_KEY);
        String emailFrom = JetspeedResources.getString("mail.support", "david@bluesunrise.com");
        String emailTo = rundata.getParameters().getString("emailTo", "jetspeed-dev@jakarta.apache.org");
        String emailAttachment = rundata.getRequest().getParameter("emailAttachment");
        try
        {
            String emailText = emailBody.toString();

            // Create the JavaMail session
            java.util.Properties properties = System.getProperties();
            properties.put("mail.smtp.host", emailSmtp);
            Session emailSession = Session.getInstance(properties, null);

            // Construct the message
            MimeMessage message = new MimeMessage(emailSession);

            // Set the from address
            Address fromAddress = new InternetAddress(emailFrom);
            message.setFrom(fromAddress);

            // Parse and set the recipient addresses
            Address[] toAddresses = InternetAddress.parse(emailTo);
            message.setRecipients(Message.RecipientType.TO, toAddresses);

            // Set the subject and text
            message.setSubject("Jetspeed Questionnaire from " + rundata.getUser().getEmail());
            message.setText(emailText);

            // Attach file with message
            if (emailAttachment != null)
            {
                File file = new File(emailAttachment);
                if (file.exists())
                {
                    // create and fill the first message part
                    MimeBodyPart mbp1 = new MimeBodyPart();
                    mbp1.setText(emailText);

                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(emailAttachment);
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(fds.getName());

                    // create the Multipart and its parts to it
                    Multipart mp = new MimeMultipart();
                    mp.addBodyPart(mbp1);
                    mp.addBodyPart(mbp2);

                    // add the Multipart to the message
                    message.setContent(mp);
                }
                else
                {
                    message.setText(emailBody.toString());
                }
            }

            // send the message
            Transport.send(message);

            // Display confirmation
            rundata.getRequest().setAttribute("email", emailBody.toString());
            String confirmTemplate = portlet.getPortletConfig().getInitParameter("confirm.template", 
                                                                                 "JetspeedQuestionnaireConfirmation.jsp");
           // this.setTemplate(rundata, portlet, confirmTemplate);
            setTemplate(rundata, confirmTemplate, true);

            rundata.setMessage("Email successfully sent");
        }
        catch (Exception e)
        {
            Log.error(e);
            rundata.setMessage("Error sending email: " + e);
        }

        //buildNormalContext(portlet, rundata);

    }


}

