/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.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 1any 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
 *
 * Initial developer(s): Florent BENOIT & Ludovic BERT
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.mail.factory;

//import java
import java.io.Serializable;
import java.util.Properties;

import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.Referenceable;

import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.common.PropDump;
import org.objectweb.jonas.mail.MailService;
import org.objectweb.jonas.mail.MailServiceImpl;
import org.objectweb.jonas.service.ServiceManager;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * This class implements JOnAS mail factory objects. It gets the properties from mail factory properties file
 * and build a properties object for the Session.
 * @author Florent Benoit
 * @author Ludovic Bert
 * Contributor(s):
 * Adriana Danes :
 * Refactor code: rename the management methods (use straightforward
 * names, as they are to be used in a Management Console)
 * 03/04/01 : JavaMail extends ReconfigDispatcher in order to send reconfiguration Notifications to ReconfigManager
 *
 * Markus Karg : Change the JOnAS mail factory initialisation strategy in order
 * to allow any initialisation parameters for a javax.mail.Session object (not
 * only a known set pf initialisation parameters as before).
 *
 * Adriana Danes :
 * 03/11/20 : J2EEManagement conformance - replaces old JMail class
 */
public abstract class JavaMail implements Serializable, Referenceable {

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

    /**
     * The name of the factory.
     */
    private String factoryName = null;

    /**
     * The jndi name of this object.
     */
    private String name = null;

    /**
     * Properties for the javax.mail.Session object.
     * Keep only the values used for configuring the javax.mail.Session object.
     */
    private Properties mailSessionProperties = null;

    /**
     * Properties for the authentication.
     */
    private Properties authenticationProperties = null;

    /**
     * JOnAS-specific property that authenticates the user name
     */
    private static final String PROPERTY_AUTHENTICATION_USERNAME = "mail.authentication.username";

    /**
     * JOnAS-specific property that authenticates the user password
     */
    private static final String PROPERTY_AUTHENTICATION_PASSWORD = "mail.authentication.password";

    /**
     * Constructor of a JavaMail Object with the given name and properties.
     * @param factoryName the name of the factory.
     * @param name the jndi name.
     * @param mailProperties properties for configuring and manageing this object.
     */
    public JavaMail(String factoryName, String name, Properties mailProperties) {
        //Get the logger
        if (logger == null) {
            logger = Log.getLogger(Log.JONAS_MAIL_PREFIX);
        }
        this.factoryName = factoryName;
        this.name = name;

        this.mailSessionProperties = (Properties) mailProperties.clone();

        // Retrieve JOnAS specific properties 'type' and 'name' from props
        mailSessionProperties.remove(MailServiceImpl.PROPERTY_NAME);
        mailSessionProperties.remove(MailServiceImpl.PROPERTY_TYPE);

        // Construct authentication properties from well-known JOnAS properties only
        this.authenticationProperties = new Properties();
        String propValue = null;
        propValue = (String) mailSessionProperties.remove(PROPERTY_AUTHENTICATION_USERNAME);
        if (propValue != null) {
            authenticationProperties.setProperty(PROPERTY_AUTHENTICATION_USERNAME, propValue);
        }
        propValue = (String) mailSessionProperties.remove(PROPERTY_AUTHENTICATION_PASSWORD);
        if (propValue != null) {
            authenticationProperties.setProperty(PROPERTY_AUTHENTICATION_PASSWORD, propValue);
        }
    }


    /**
     * Return the jndi name of this object
     * @return the jndi name
     */
    public String getName() {
        return name;
    }

    /**
     * Set the jndi name of this object.
     * @param name the jndi name
     */
    void setName(String name) {
        String oldName = this.name;
        this.name = new String(name);
        try {
            ((MailService) ServiceManager.getInstance().getMailService()).renameJavaMailFactory(oldName, this);
        } catch (Exception e) {
            // should never occurs at this time
        }
    }

    /**
     * Return the name of this mail factory
     * @return name of this mail factory.
     */
    public String getFactoryName() {
        return factoryName;
    }

    /**
     * Return the type of the factory
     * @return the type of the mail factory
     */
    public abstract String getType();


    /**
     * Retrieves the session properties of this object.
     * @return the session properties of this object.
     */
    Properties getSessionProperties() {
        return mailSessionProperties;
    }

    /**
     * Set the session properties.
     * @param props the session properties.
     */
    void setSessionProperties(Properties props) {
        this.mailSessionProperties = props;
        // rebind the mail factory in JNDI
        try {
            ((MailService) ServiceManager.getInstance().getMailService()).recreateJavaMailFactory(this);
        } catch (Exception e) {
            // should never occurs
        }
        //notifyReconfiguration(props);
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            PropDump.print("These are the udated session properties", this.mailSessionProperties, logger, BasicLevel.DEBUG);
        }
    }

    /**
     * Retrieves the authentication properties of this object.
     * @return the authentication properties of this object.
     */
    Properties getAuthenticationProperties() {
        return authenticationProperties;
    }

    /**
     * Set the authentication properties.
     * @param props the authentication properties.
     */
    void setAuthenticationProperties(Properties props) {
        this.authenticationProperties = props;
        // rebind the mail factory in JNDI
        try {
            ((MailService) ServiceManager.getInstance().getMailService()).recreateJavaMailFactory(this);
        } catch (Exception e) {
            // should never occurs
        }
        //notifyReconfiguration(props);
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            PropDump.print("These are the udated auth properties",
                       this.authenticationProperties, logger, BasicLevel.DEBUG);
        }
    }

    /**
     * Retrieves the Reference of the object.
     * The Reference contains the factory used to create this object
     * and the optional parameters used to configure the factory.
     * @return the non-null Reference of the object.
     * @throws NamingException if a naming exception was encountered while
     * retrieving the reference.
     */
    public abstract Reference getReference() throws NamingException;


    /**
     * @return Returns the logger.
     */
    public static Logger getLogger() {
        return logger;
    }
    /**
     * @param logger The logger to set.
     */
    public static void setLogger(Logger logger) {
        JavaMail.logger = logger;
    }
    /**
     * @return Returns the mailSessionProperties.
     */
    public Properties getMailSessionProperties() {
        return mailSessionProperties;
    }
    /**
     * @param mailSessionProperties The mailSessionProperties to set.
     */
    public void setMailSessionProperties(Properties mailSessionProperties) {
        this.mailSessionProperties = mailSessionProperties;
    }
}

