/*
 * 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.inbox.InboxHelper;
import com.queplix.core.modules.inbox.InboxMessage;
import com.queplix.core.modules.inbox.ejb.InboxManagerLocal;
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.utils.StringHelper;

/**
 * Inital mail filter.
 *
 * @author Konstantin Mironov
 * @since 8 Dec 2006
 */
public class InitialFilter extends AbstractMailFilter {

    /*
     * No javadoc
     * @see MailFilter#filterMail
     */
    public boolean filterMail(InboxMessage inboxMessage) {

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

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

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

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

        //
        // Checking message.
        //

        boolean acceptMail = true;

        if(inboxMessage.getTo() == null) {
            acceptMail = false;
            logDetailMessage = "There is no 'To' address.";

        } else if(inboxMessage.getFrom() == null) {
            acceptMail = false;
            logDetailMessage = "There is no 'From' address.";

        } else if(StringHelper.isEmpty(inboxMessage.getSubject())) {
            acceptMail = false;
            logDetailMessage = "There is no Subject.";
        } // if (message.getTo() == null)

        //
        // Parse headers.
        //
        // 1. Try to find mailer.
        String quewebMailer = InboxHelper.getMailer();
        if(quewebMailer != null) {
            String[] values = inboxMessage.getHeader(
                    InboxHelper.HEADER_X_MAILER);
            if(values != null) {
                for(int i = 0; i < values.length; i++) {
                    String value = values[i];
                    if(quewebMailer.equalsIgnoreCase(value)) {
                        // Found QueWeb mailer header.
                        inboxMessage.quewebMailer();

                        logMessage = "Message was sent by QueWeb App";
                        INFO(logID + logMessage + ". Message: " + inboxMessage);
                        inboxPublisher.INFO(logMessage, inboxMessage);

                        break;
                    } // if (quewebMailer.equalsIgnoreCase(value))
                } // for (int i = 0; i < values.length; i++)
            } // if (values != null)
        } // if (quewebMailer != null)

        // 2. Looking for linked object using headers -- only for QueWeb messages.
        if(inboxMessage.isQuewebMailer()) {
            String[] values = inboxMessage.getHeader(
                    InboxHelper.HEADER_X_TIKET);
            if(values != null && values.length > 0) {
                // Found X-ticket mailer header.
                // object ID and object Type can be separated by ','
                Long objectId = null;
                Integer objectType = null;
                String value = values[0];
                String[] tokens = StringHelper.split(value, ",");
                if(tokens == null) {
                    throw new NullPointerException("Cannot split " + InboxHelper
                            .HEADER_X_TIKET + " header '" + value + "'.");
                }
                try {
                    if(tokens.length == 1) {
                        objectId = new Long(tokens[0]);
                    } else if(tokens.length == 2) {
                        objectId = new Long(tokens[0]);
                        objectType = new Integer(tokens[1]);
                    }
                } catch (Exception ex) {
                    logMessage = "Cannot parse " + InboxHelper.HEADER_X_TIKET
                            + " header '" + value + "'.";
                    WARN(logID + logMessage + ". Error: " + ex.getMessage());
                    inboxPublisher.WARN(logMessage, inboxMessage);
                } // try

                if(objectId != null) {
                    // Header parsed properly -- set linked object.
                    inboxMessage.setObjectInfo(objectId, objectType);
                    inboxMessage.setIsNewObject(false);

                    if(objectType != null) {
                        logMessage = "Message has linked object: " + objectId
                                + " [" + objectType + "]";
                    } else {
                        logMessage = "Message has linked object: " + objectId;
                    }
                    INFO(logID + logMessage + ". Message: " + inboxMessage);
                    inboxPublisher.INFO(logMessage, inboxMessage);
                } // if (callId != null)
            } // if (values != null && values.length > 0)
        } // if (message.isQuewebMailer())

        if(!acceptMail) {
            //
            // Rejected - log problem.
            //

            logMessage = "Message is corrupt. ";
            WARN(logID + logMessage + logDetailMessage + ". Message: "
                    + inboxMessage);
            inboxPublisher.WARN(logMessage + logDetailMessage, inboxMessage);

            // Saving to TRASH.
            local.saveMailToTrash(getLogonSession(), inboxMessage);
        } // if (!acceptMail)

        inboxPublisher.DEBUG("Email Initial filter was finished...");
        // Ok.
        return acceptMail;

    } // filterMail()

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

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

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

} // class InitialFilter extends AbstractMailFilter
