/**
 * 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: AbstractJavaMail.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */

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

//import java
import java.util.Properties;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.jonas.lib.util.Log;
import org.ow2.jonas.lib.util.PropDump;
import org.ow2.jonas.mail.MailService;
import org.ow2.jonas.mail.factory.JavaMail;

/**
 * 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)
 *
 * 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 AbstractJavaMail implements JavaMail {

    /**
     * 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;

    /**
     * TODO - doc
     */
    private MailService mailService = 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 AbstractJavaMail(final String factoryName, final String name, final Properties mailProperties, final MailService mailService) {
        //Get the logger
        if (logger == null) {
            logger = Log.getLogger(Log.JONAS_MAIL_PREFIX);
        }
        this.factoryName = factoryName;
        this.name = name;
        this.mailService = mailService;

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

        // Retrieve JOnAS specific properties 'type' and 'name' from props
        mailSessionProperties.remove(MailService.PROPERTY_NAME);
        mailSessionProperties.remove(MailService.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);
        }
    }


    /* (non-Javadoc)
     * @see org.ow2.jonas.mail.internal.factory.JavaMail#getName()
     */
    public String getName() {
        return name;
    }

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

    /* (non-Javadoc)
     * @see org.ow2.jonas.mail.internal.factory.JavaMail#getFactoryName()
     */
    public String getFactoryName() {
        return factoryName;
    }

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

    /**
     * Set the session properties.
     * @param props the session properties.
     */
    public void setSessionProperties(Properties props) {
        this.mailSessionProperties = props;
        // rebind the mail factory in JNDI
        try {
            //((MailService) ServiceManager.getInstance().getMailService()).recreateJavaMailFactory(this);
            mailService.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.
     */
    public Properties getAuthenticationProperties() {
        return authenticationProperties;
    }

    /**
     * Set the authentication properties.
     * @param props the authentication properties.
     */
    public void setAuthenticationProperties(Properties props) {
        this.authenticationProperties = props;
        // rebind the mail factory in JNDI
        try {
            //((MailService) ServiceManager.getInstance().getMailService()).recreateJavaMailFactory(this);
            mailService.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);
        }
    }

    /**
     * @return Returns the logger.
     */
    public static Logger getLogger() {
        return logger;
    }

    /**
     * @param logger The logger to set.
     */
    public static void setLogger(final Logger logger) {
        AbstractJavaMail.logger = logger;
    }

    /* (non-Javadoc)
     * @see org.ow2.jonas.mail.internal.factory.JavaMail#getMailSessionProperties()
     */
    public Properties getMailSessionProperties() {
        return mailSessionProperties;
    }

    /* (non-Javadoc)
     * @see org.ow2.jonas.mail.internal.factory.JavaMail#setMailSessionProperties(java.util.Properties)
     */
    public void setMailSessionProperties(Properties mailSessionProperties) {
        this.mailSessionProperties = mailSessionProperties;
    }


    public MailService getMailService() {
        return mailService;
    }
}

