/*
 * 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.error.GenericSystemException;
import com.queplix.core.integrator.security.LogonSession;
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.FilterLogPublisher;
import com.queplix.core.modules.jeo.JEObjectHandler;
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.jeo.gen.InboxObjectHandler;
import com.queplix.core.modules.mail.MailAddress;
import com.queplix.core.utils.JNDINames;
import com.queplix.core.utils.cache.CacheObjectManager;

/**
 * This is error hendler for email filtering.
 *
 * @author Konstantin Mironov
 * @since 8 Dec 2006
 */
public class ErrorHndFilter extends AbstractMailFilter {

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

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

    public boolean filterMail(InboxMessage inboxMessage) {

        inboxPublisher.DEBUG("Email Error hendler filter is started...");

        // Getting the message data.
        Long messageId = inboxMessage.getMessageId();
        LogonSession ls = getLogonSession();
        MailAddress fromReply;
        Long autoreplyID;
        MailAddress[] toReply = MailAddress.parse(
                inboxMessage.getFrom().getEmail());

        // Init InboxManager.
        InboxManagerLocal local = getInboxManager();

        // Generate message ID.
        boolean exist = true;
        if(messageId == null) {
            // .. get next unique ID from database.
            long l = local.getUniqueMessageID();
            messageId = new Long(l);
            inboxMessage.setMessageId(messageId);
            exist = false;
        } // if (messageId == null)

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

        try {
            // Check whether record saved to database.
            if(exist) {
                JEOManagerLocal jeoMgr = getJEOManager();
                JEObjectHandler hnd = InboxObjectHandler.selectByPkey(jeoMgr,
                        ls, messageId.longValue());
                exist = (hnd != null);
            }

            if(!exist) {
                // Not saved.
                // By default save to TRASH.
                local.saveMailToTrash(ls, inboxMessage);
            }

            // send autoreply error
            // 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)
            autoreplyID = accountObj.getAutoreply_id();
            if(autoreplyID == null) {
                INFO("Autoreply isn't set.");
                return true;
            } else {
                INFO("Default Autoreply ID is " + autoreplyID);
            } // if (autoreplyID == null)
            AutoreplyObject autoreplyObj = AutoreplyObjectHandler.selectByPkey(
                    getJEOManager(), getLogonSession(),
                    autoreplyID.longValue());
            fromReply = new MailAddress(autoreplyObj.getReply_email());
            InboxMessage autoreplyMessage;
            autoreplyMessage = new InboxMessage(toReply, fromReply,
                    autoreplyObj.getFail_subject(), new String(
                    autoreplyObj.getFail_body()));

            InboxManagerLocal localInboxManager = getLocalInboxManager();

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

        } catch (Exception ex) {
            // Logging and re-throwing the exception.
            logMessage = "Processing message failed due to error: " + ex
                    .getMessage();
            inboxPublisher.ERROR(logMessage, inboxMessage);
            ERROR(logID + logMessage);

            throw new GenericSystemException(ex);
        } // try

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

    } // filterMail(InboxMessage) : boolean

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

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

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

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

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

} // class ErrorHndFilter
