/*
 * 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.inbox.utils.filters;

import com.queplix.core.modules.eql.error.EQLException;
import com.queplix.core.modules.inbox.InboxMessage;
import com.queplix.core.modules.inbox.ejb.InboxManagerLocal;
import com.queplix.core.modules.inbox.ejb.InboxManagerLocalHome;
import com.queplix.core.modules.inbox.utils.AbstractMailFilter;
import com.queplix.core.modules.inbox.utils.log.AbstractInboxLogPublisher;
import com.queplix.core.modules.inbox.utils.log.AutoreplyLogPublisher;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocal;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocalHome;
import com.queplix.core.modules.jeo.gen.AccountObject;
import com.queplix.core.modules.jeo.gen.AccountObjectHandler;
import com.queplix.core.modules.jeo.gen.AutoreplyObject;
import com.queplix.core.modules.jeo.gen.AutoreplyObjectHandler;
import com.queplix.core.modules.mail.MailAddress;
import com.queplix.core.utils.JNDINames;
import com.queplix.core.utils.cache.CacheObjectManager;

import javax.mail.MessagingException;

/**
 * Auto reply filter.
 *
 * @author Konstantin Mironov
 * @since 8 Dec 2006
 */
public class AutoReplyFilter extends AbstractMailFilter {

    // ------------------------------------------------------- Main method

    /*
     * No javadoc
     * @see MailFilter#filterMail
     */

    public boolean filterMail(InboxMessage inboxMessage) {

        inboxPublisher.DEBUG("Email Autoreply filter is started...");

        // Getting the message data.
        Long autoreplyID = inboxMessage.getAutoreplyId();
        MailAddress from = inboxMessage.getFrom();
        MailAddress[] toReply = MailAddress.parse(from.getEmail());
        MailAddress fromReply;

        // Init log data.
        String logMessage;
        String logID = makeLogID(inboxMessage.getMessageId());

        try {
            // try to get default autoreply using account
            AccountObject accountObj = AccountObjectHandler.selectByPkey(
                    getJEOManager(), getLogonSession(),
                    inboxMessage.getAccountId().longValue());
            if(accountObj == null) {
                logMessage = "The account wasn't found. The account ID is "
                        + inboxMessage.getAccountId() +
                        " The autoreply wasn't sent.";
                inboxPublisher.ERROR(logMessage, inboxMessage);
                ERROR(logID + logMessage);
                return true;
            } // if (accountObj == null)

            if(autoreplyID == null) {
                autoreplyID = accountObj.getAutoreply_id();
                if(autoreplyID == null) {
                    INFO("Autoreply isn't set.");
                    return true;
                } else {
                    INFO("Default Autoreply ID is " + autoreplyID);
                } // if (autoreplyID == null)
            } else {
                INFO("Autoreply ID is " + autoreplyID);
            } // if (autoreplyID == null)

            AutoreplyObject autoreplyObj = AutoreplyObjectHandler.selectByPkey(
                    getJEOManager(), getLogonSession(),
                    autoreplyID.longValue());
            fromReply = new MailAddress(autoreplyObj.getReply_email());
            InboxMessage autoreplyMessage;
            if(inboxMessage.isNewObject()) {
                autoreplyMessage = new InboxMessage(toReply, fromReply,
                        autoreplyObj.getSuccessful_subject(), new String(
                        autoreplyObj.getSuccessful_body()));
            } else {
                autoreplyMessage = new InboxMessage(toReply, fromReply,
                        autoreplyObj.getUpdate_subject(), new String(
                        autoreplyObj.getUpdate_body()));
            }

            InboxManagerLocal localInboxManager = getLocalInboxManager();

            localInboxManager.sendEmailMessage(getLogonSession(),
                    autoreplyMessage, null);

        } catch (EQLException eqlex) {
            // Logging the exception.
            logMessage = "Autoreply sending failed due to EQL error: "
                    + eqlex.getMessage() +
                    " The autoreply wasn't sent.";
            inboxPublisher.ERROR(logMessage, inboxMessage);
            ERROR(logID + logMessage);
            return true;
        } catch (MessagingException mex) {
            // Logging the exception.
            logMessage =
                    "Autoreply sending failed due to Messaging Exception error: "
                            + mex.getMessage() +
                            " The autoreply wasn't sent.";
            inboxPublisher.ERROR(logMessage, inboxMessage);
            ERROR(logID + logMessage);
            return true;
        } // try-catch

        // Ok.
        inboxPublisher.DEBUG("Email Autoreply filter was finished...");
        return true;

    } // filterMail()

    // ------------------------------------------------------- Protected methods

    /*
     * No javadoc
     * @see AbstractMailFilter#createInboxLogPublisher
     */

    protected AbstractInboxLogPublisher createInboxLogPublisher() {
        return new AutoreplyLogPublisher(getLogonSession());
    }

    /**
     * JEOManagerLocal getter.
     *
     * @return JEOManagerLocal
     */
    protected JEOManagerLocal getJEOManager() {
        CacheObjectManager com = new CacheObjectManager();
        return (JEOManagerLocal) com.getLocalObject(JNDINames.JEOManager,
                JEOManagerLocalHome.class);
    } // getJEOManager() : JEOManagerLocal

    /**
     * InboxManagerLocal getter.
     *
     * @return InboxManagerLocal
     */
    protected InboxManagerLocal getLocalInboxManager() {
        CacheObjectManager com = new CacheObjectManager();
        return (InboxManagerLocal) com.getLocalObject(JNDINames.InboxManager,
                InboxManagerLocalHome.class);
    } // getInboxManager() : InboxManagerLocal

} // end of class
