/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This 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 (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.mail.internal.factory.template;

import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.xwiki.localization.LocaleUtils;
import org.xwiki.mail.ExtendedMimeMessage;
import org.xwiki.mail.MimeBodyPartFactory;
import org.xwiki.mail.internal.factory.AbstractMimeMessageFactory;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.properties.ConverterManager;

/**
 * Creates a Mime Message with the subject pre-filled with the evaluated "subject" xproperty found in an "XWiki.Mail"
 * xobject located in the template document pointed to by the passed reference.
 *
 * @version $Id$
 * @since 6.1RC1
 */
public abstract class AbstractTemplateMimeMessageFactory extends AbstractMimeMessageFactory<MimeMessage>
{
    @Inject
    private ConverterManager converterManager;

    /**
     * @return the Template Manager instance to use, this allows passing either the default component implementation or
     * a secure one for scripts
     */
    protected abstract MailTemplateManager getTemplateManager();

    /**
     * @return the Body Part Factory instance to use, this allows passing either the default component implementation or
     * a secure one for scripts
     */
    protected abstract MimeBodyPartFactory<DocumentReference> getMimeBodyPartFactory();

    @Override
    public MimeMessage createMessage(Object templateReferenceObject, Map<String, Object> parameters)
        throws MessagingException
    {
        DocumentReference templateReference = getTypedSource(templateReferenceObject, DocumentReference.class);

        // Note: We don't create a Session here ATM since it's not required. The returned MimeMessage will be
        // given a valid Session when it's deserialized from the mail content store for sending.
        ExtendedMimeMessage message = new ExtendedMimeMessage();

        // Handle optional "from" address.
        Address from = this.converterManager.convert(Address.class, parameters.get("from"));
        if (from != null) {
            message.setFrom(from);
        }

        // Handle optional "to", "cc" and "bcc" addresses.
        setRecipient(message, Message.RecipientType.TO, parameters.get("to"));
        setRecipient(message, Message.RecipientType.CC, parameters.get("cc"));
        setRecipient(message, Message.RecipientType.BCC, parameters.get("bcc"));

        // Handle optional "type" parameter to set the mail type
        // Set the Message type if passed in parameters
        String type = (String) parameters.get("type");
        if (type != null) {
            message.setType(type);
        }

        // Handle the subject. Get it from the template
        Map<String, Object> velocityVariables = (Map<String, Object>) parameters.get("velocityVariables");
        Locale locale = getLocale(parameters.get("language"));
        String subject = getTemplateManager().evaluate(templateReference, "subject", velocityVariables, locale);
        message.setSubject(subject);

        // Add a default body part taken from the template.
        Multipart multipart = new MimeMultipart("mixed");
        multipart.addBodyPart(getMimeBodyPartFactory().create(templateReference, parameters));
        message.setContent(multipart);

        return message;
    }

    private Locale getLocale(Object languageValue)
    {
        Locale locale;
        // Note: we support both a Locale type and String mostly for backward-compatibility reasons (the first version
        // of this API only supported String and we've moved to support Locale).
        if (languageValue instanceof Locale) {
            locale = (Locale) languageValue;
        } else {
            locale = LocaleUtils.toLocale(languageValue.toString());
        }
        return locale;
    }

    private void setRecipient(MimeMessage message, Message.RecipientType type, Object value)
        throws MessagingException
    {
        Address[] addresses = this.converterManager.convert(Address[].class, value);
        if (addresses != null) {
            message.setRecipients(type, addresses);
        }
    }
}

@@ -4452,24 +4452,117 @@
 ale locale;%0A
+%0A        if (languageValue == null) %7B%0A            locale = Locale.ROOT;%0A        %7D else %7B%0A    
         // N
@@ -4663,17 +4663,13 @@
 irst
- version%0A
+%0A    
     
@@ -4674,16 +4674,24 @@
       //
+ version
  of this
@@ -4753,16 +4753,20 @@
 ocale).%0A
+    
         
@@ -4808,32 +4808,36 @@
 ) %7B%0A            
+    
 locale = (Locale
@@ -4853,32 +4853,36 @@
 eValue;%0A        
+    
 %7D else %7B%0A       
@@ -4878,32 +4878,36 @@
 e %7B%0A            
+ 
+   
 locale = LocaleU
@@ -4943,24 +4943,38 @@
 oString());%0A
+            %7D%0A
         %7D%0A  

Remove remaining ambiguity from Locale/language related api.* script API * Fix potential NPE that the previous commit will cause when no "language" parameter is passed