/*
 * 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.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.db.DBRealmManager;
import com.queplix.core.modules.inbox.utils.log.AbstractInboxLogPublisher;
import com.queplix.core.modules.inbox.utils.log.FilterLogPublisher;
import com.queplix.core.modules.mail.MailAddress;
import com.queplix.core.utils.StringHelper;
import com.queplix.core.utils.sql.SqlWrapper;
import com.queplix.core.utils.sql.SqlWrapperFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Description.
 *
 * @author Konstantin Mironov
 * @since 8 Dec 2006
 */
public class RejectFilter extends AbstractMailFilter {

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

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

    public boolean filterMail(InboxMessage inboxMessage) {

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

        boolean acceptMail = true;

        // Getting the message data.
        long accountID = inboxMessage.getAccountId().longValue();
        String to = MailAddress.toRfcString(inboxMessage.getTo());
        String from = inboxMessage.getFrom().toRfcString();
        String subject = inboxMessage.getSubject();
        String body = inboxMessage.getBody();

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

        // get filters.
        String sql = DBRealmManager.getSql("get_account_filters");
        SqlWrapper sqlWrapper = SqlWrapperFactory.getSqlWrapper();
        Connection con = null;
        PreparedStatement stat = null;

        // Go!
        try {
            // Connecting.
            con = sqlWrapper.doConnection();

            // Getting filters list for this account.
            stat = sqlWrapper.doPreparedStatement(con, sql);
            stat.setLong(1, accountID);
            ResultSet rs = sqlWrapper.executeQuery(stat);

            while(rs.next()) {

                // Getting filter ID.
                long filterID = rs.getLong(1);

                // What to check for?
                String word = rs.getString(2);
                if(StringHelper.isEmpty(word)) {
                    DEBUG(logID + "Skipping filter #" + filterID
                            + " - empty keyword.");
                    continue;
                } // if (StringHelper.isEmpty(word))

                // Where to check?
                boolean checkFrom = (rs.getInt(3) > 0);
                boolean checkTo = (rs.getInt(4) > 0);
                boolean checkSubject = (rs.getInt(5) > 0);
                boolean checkBody = (rs.getInt(6) > 0);

                // Checking...
                if(checkFrom && StringHelper.find(from, word)) {
                    logDetailMessage = "Word '" + word
                            + "' found in 'from' field.";
                    inboxMessage.setFilterId(new Long(filterID));
                    acceptMail = false;

                } else if(checkTo && StringHelper.find(to, word)) {
                    logDetailMessage = "Word '" + word
                            + "' found in 'to' field.";
                    inboxMessage.setFilterId(new Long(filterID));
                    acceptMail = false;

                } else if(checkSubject && StringHelper.find(subject, word)) {
                    logDetailMessage = "Word '" + word
                            + "' found in message subject.";
                    inboxMessage.setFilterId(new Long(filterID));
                    acceptMail = false;

                } else if(checkBody && StringHelper.find(body, word)) {
                    logDetailMessage = "Word '" + word
                            + "' found in message body.";
                    inboxMessage.setFilterId(new Long(filterID));
                    acceptMail = false;
                } // if (checkFrom && StringHelper.find(from, word))

                // Was the filter fired?
                if(!acceptMail) {
                    // Log problem and break cycle.
                    logMessage = "Message was filtered out. ";
                    INFO(logID + logMessage + logDetailMessage + ". Filter #"
                            + filterID + ". Message: " + inboxMessage);
                    inboxPublisher.INFO(logMessage + logDetailMessage,
                            inboxMessage);
                    break;
                } // if (!acceptMail)

            } // while
        } catch (SQLException sqlex) {
            // Logging and re-throwing the exception.
            logMessage = "Filtering failed due to SQL error: " + sqlex
                    .getMessage();
            inboxPublisher.ERROR(logMessage, inboxMessage);
            ERROR(logID + logMessage);

            throw new GenericSystemException(sqlex);

        } finally {

            // Close connection.
            sqlWrapper.closeConnection(con, stat);
            if(!acceptMail) {
                // Saving to TRASH.
                InboxManagerLocal local = getInboxManager();
                local.saveMailToTrash(getLogonSession(), inboxMessage);
            } // if (!acceptMail)
        } // try-catch

        // Ok.
        inboxPublisher.DEBUG("Email Reject filter was finished...");
        return acceptMail;
    } // filterMail(InboxMessage) : boolean

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

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

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

} // end of class
