/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2007 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.mail.internal.factory;


//import java
import java.util.Hashtable;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimePart;
import javax.mail.internet.MimePartDataSource;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

import org.ow2.jonas.lib.util.JNDIUtils;
import org.ow2.jonas.lib.util.Log;
import org.ow2.jonas.lib.util.PropDump;
import org.ow2.jonas.mail.internal.factory.lib.JAuthenticator;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * This class provides an implementation of a mime part data source factory
 * for sending mail.
 * @author Ludovic Bert
 * @author Florent Benoit
 */
public class JavaMailMimePartDSFactory implements ObjectFactory {

    /**
     * The Java type for which this factory knows how to create objects.
     */
    protected static final String FACTORY_TYPE = "javax.mail.internet.MimePartDataSource";

    /**
     * The logger used in JOnAS.
     */
    private static Logger logger = null;

    /**
     * Creates a javax.mail.MimePartDataSource object using the location or
     * reference information specified.
     * @param obj the possibly null object containing location or reference
     * information that can be used in creating an object.
     * @param name the name of this object relative to nameCtx, or null if no
     * name is specified.
     * @param nameCtx the context relative to which the name parameter is
     * specified, or null if name is relative to the default initial context.
     * @param environment the possibly null environment that is used in
     * creating the object.
     * @return a newly created javax.mail.internet.MimePartDataSource object with the
     * specific configuration; null if an object cannot be created.
     * @throws Exception if this object factory encountered an exception
     * while attempting to create an object, and no other object factories are
     * to be tried.
     */
    public Object getObjectInstance(Object obj, Name name, Context nameCtx,
                                    Hashtable environment) throws Exception {

        //Get the logger
        if (logger == null) {
            logger = Log.getLogger(Log.JONAS_MAIL_PREFIX);
        }

        //Get the reference
        Reference ref = (Reference) obj;

        //Get the class name
        String clname = ref.getClassName();

        //Check the class name
        if (!ref.getClassName().equals(FACTORY_TYPE)) {
            logger.log(BasicLevel.ERROR, "Cannot create object : required type is '" + FACTORY_TYPE + "', but found type is '" + clname + "'.");
            return (null);
        }

        Properties sessionProps = new Properties();
        Properties mimeMessageProps = new Properties();
        Properties authenticationProps = new Properties();
        RefAddr refAddr = null;

        refAddr =  ref.get("javaxmailSession.properties");
        if (refAddr != null) {
            sessionProps = (Properties) JNDIUtils.getObjectFromBytes((byte[]) refAddr.getContent());
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                PropDump.print("These are the properties used to obtain a new Session object", sessionProps, logger, BasicLevel.DEBUG);
            }
        }

        refAddr =  ref.get("javaxInternetMimeMessage.properties");
        if (refAddr != null) {
            mimeMessageProps = (Properties) JNDIUtils.getObjectFromBytes((byte[]) refAddr.getContent());
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                PropDump.print("These are the properties specific to Internet mail",
                        mimeMessageProps, logger, BasicLevel.DEBUG);
            }
        }

        refAddr =  ref.get("authentication.properties");
        if (refAddr != null) {
            authenticationProps = (Properties) JNDIUtils.getObjectFromBytes((byte[]) refAddr.getContent());
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                PropDump.print("These are the authentication properties",
                           authenticationProps, logger, BasicLevel.DEBUG);
            }
        }

        //username (Authentication)
        String mailAuthenticationUsername =  authenticationProps.getProperty("mail.authentication.username");

        //Password (Authentication)
        String mailAuthenticationPassword = authenticationProps.getProperty("mail.authentication.password");

        //Field 'to'
        String mailTo = mimeMessageProps.getProperty("mail.to");
        InternetAddress[] toRecipients = null;
        if (mailTo != null) {
            toRecipients = getInternetAddressFromString(mailTo);
        }

        //Field 'cc'
        String mailCc = mimeMessageProps.getProperty("mail.cc");
        InternetAddress[] ccRecipients = null;
        if (mailCc != null) {
            ccRecipients = getInternetAddressFromString(mailCc);
        }

        //Field 'bcc'
        String mailBcc = mimeMessageProps.getProperty("mail.bcc");
        InternetAddress[] bccRecipients = null;
        if (mailBcc != null) {
            bccRecipients = getInternetAddressFromString(mailBcc);
        }

        //Field 'subject'
        String mailSubject = mimeMessageProps.getProperty("mail.subject");


        JAuthenticator jAuthenticator = null;
        if ((mailAuthenticationUsername != null) && (mailAuthenticationPassword != null)) {
            jAuthenticator = new JAuthenticator(mailAuthenticationUsername, mailAuthenticationPassword);
        }

        //Build the message from the Session.
        MimeMessage mimeMessage = new MimeMessage(Session.getInstance(sessionProps, jAuthenticator));

        //And set the properties if there are not null

        //Field 'to'
        if (toRecipients != null) {
            mimeMessage.setRecipients(Message.RecipientType.TO, toRecipients);
        }

        //Field 'cc'
        if (ccRecipients != null) {
            mimeMessage.setRecipients(Message.RecipientType.CC, ccRecipients);
        }

        //Field 'bcc'
        if (bccRecipients != null) {
            mimeMessage.setRecipients(Message.RecipientType.BCC, bccRecipients);
        }

        //Field 'subject'
        if (mailSubject != null) {
            mimeMessage.setSubject(mailSubject);
        }

        MimePartDataSource mimePartDS = new MimePartDataSource((MimePart) mimeMessage);
        return mimePartDS;
    }

    /**
     * Convert a comma separated list into an array of InternetAddress.
     * @param txt acomma separated string
     * @return an array of InternetAddress
     */

    private static InternetAddress[] getInternetAddressFromString(String txt) {
        if (txt == null) {
            return null;
        }
        StringTokenizer st = new StringTokenizer(txt, ",");
        InternetAddress[] addresses = new InternetAddress[st.countTokens()];
        int i = 0;
        try {
            while (st.hasMoreTokens()) {
                addresses[i] = new InternetAddress((String) st.nextToken());
                i++;
            }
        } catch (Exception e) {
            return null;
        }
        return addresses;
    }
}
