/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.core.modules.mail.www;

import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.integrator.security.User;
import com.queplix.core.integrator.security.WebLoginManager;
import com.queplix.core.modules.mail.MailAddress;
import com.queplix.core.modules.mail.MailMessage;
import com.queplix.core.modules.mail.ejb.MailManagerLocal;
import com.queplix.core.modules.mail.ejb.MailManagerLocalHome;
import com.queplix.core.utils.JNDINames;
import com.queplix.core.utils.StringHelper;
import com.queplix.core.utils.www.AbstractServlet;
import com.queplix.core.utils.www.ServletHelper;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>E-mail sender</p>
 * <strong>USAGE</strong>: <pre>GET /sys/sendMail?to=alb@domain&subj=test</pre>
 * <p><strong>Parameters</strong>:
 * <ul>
 * <li><b>from</b> - message 'from' address</li>
 * <li><b>to</b> - message 'to' address</li>
 * <li><b>cc</b> - message 'cc' address</li>
 * <li><b>bcc</b> - message 'bcc' address</li>
 * <li><b>subj</b> - message subject</li>
 * <li><b>body</b> - message body</li>
 * <li><b>process_id</b> - the unique process ID</li>
 * </ul>
 * </p>
 *
 * @author [BAA] Balandin Alexander
 * @author [ALB] Baranov Andrey
 * @author [ONZ] Oleg N. Zhovtanyuk
 * @author [SG] Sergei Gurov
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:30:50 $
 */

public class SendMailServlet
        extends AbstractServlet {

    // Service method
    public void service(HttpServletRequest request,
                        HttpServletResponse response)
            throws ServletException, IOException {

        long time = System.currentTimeMillis();

        LogonSession ls;
        try {
            ls = WebLoginManager.getLogonSession(request);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
        User user = ls.getUser();

        // 1. Getting REQUIRED parameters.
        // ===============================

        // Message 'to' address.
        String toAddr = ServletHelper.getParamAsString(request, "to");

        // Message subject.
        String subject = ServletHelper.getParamAsString(request, "subject");

        // 2. Getting OPTIONAL parameters.
        // ===============================

        // Message 'from' address.
        String fromAddr = ServletHelper.getParamAsString(request, "from",
                false);

        // Message 'cc' address.
        String ccAddr = ServletHelper.getParamAsString(request, "cc", false);

        // Message 'bcc' address.
        String bccAddr = ServletHelper.getParamAsString(request, "bcc", false);

        // Message body.
        String body = ServletHelper.getParamAsString(request, "body", false);
        body = StringHelper.unEscapeUnicode(body);

        // Process ID.
        Long processId = null;
        String s = ServletHelper.getParamAsString(request, "process_id", false);
        if(!StringHelper.isEmpty(s)) {
            processId = Long.valueOf(s);
        }

        if(logger.getLogger().isDebugEnabled()) {
            logger.DEBUG("Mail data:");
            logger.DEBUG("     'from' address = " + fromAddr);
            logger.DEBUG("     'to' address = " + toAddr);
            logger.DEBUG("     'cc' address = " + ccAddr);
            logger.DEBUG("     'bcc' address = " + bccAddr);
            logger.DEBUG("     subject = " + subject);
            logger.DEBUG("     body size = " + body.length());
            logger.DEBUG("     process ID = " + processId);
        }

        // 3. Creating the message value object.
        // =====================================

        MailAddress[] to = MailAddress.parse(toAddr);
        MailMessage message = new MailMessage(to, subject, body);

        if(!StringHelper.isEmpty(fromAddr)) {
            message.setFrom(new MailAddress(fromAddr));
        } else {
            MailAddress ma = new MailAddress(user);
            if(ma.isValid()) {
                message.setFrom(ma);
            }
        }

        if(!StringHelper.isEmpty(ccAddr)) {
            message.setCc(MailAddress.parse(ccAddr));
        }

        if(!StringHelper.isEmpty(bccAddr)) {
            message.setBcc(MailAddress.parse(bccAddr));
        }

        if(processId != null) {
            message.setProcessId(processId);
        }

        // 4. Sending the mail.
        // ===============================

        // Get MailManager local interface
        MailManagerLocal local = (MailManagerLocal)
                getLocalObject(JNDINames.MailManager,
                        MailManagerLocalHome.class);

        try {
            // Sending...
            local.sendMessage(ls, message, null);

            // Ok.
            logger.INFO("Message sent.");

        } catch (MessagingException mex) {
            // Fail.
            logger.WARN("Some problems occured during mail processing: " + mex
                    .getMessage());

            /** @todo show exception on client side */
        }

        logger.INFO("Time (ms) - " + (System.currentTimeMillis() - time));

        // Close client window in any case
        response.setContentType(ServletHelper.CONTENT_TYPE_HTML);
        response.getWriter().write("<script>window.close();</script>");
    }

} // end of class
