/****************************************************************
 * Licensed to the Apache Software Foundation (ASF) under one   *
 * or more contributor license agreements.  See the NOTICE file *
 * distributed with this work for additional information        *
 * regarding copyright ownership.  The ASF licenses this file   *
 * to you under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                 *
 *                                                              *
 * 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 org.apache.james.postage.mail;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.james.postage.result.MailProcessingRecord;
import org.apache.james.postage.result.PostageRunnerResult;

/**
 * handles the process of retrieving, analyzing, matching and finally (optionally) dismissing one
 * received message.
 */
public abstract class MailAnalyzeStrategy {

    protected static Log log = LogFactory.getLog(MailAnalyzeStrategy.class);

    private String queue = null;
    private PostageRunnerResult results = null;

    public MailAnalyzeStrategy(String receivingQueueName, PostageRunnerResult results) {
        this.queue = receivingQueueName;
        this.results = results;
    }
    
    public void handle() throws Exception { 
        MailProcessingRecord mailProcessingRecord = prepareRecord();

        MimeMessage message = loadMessage();
        
        // do we _really_ have to handle this?
        if (!MailMatchingUtils.isMatchCandidate(message)) return;

        String id = MailMatchingUtils.getMailIdHeader(message);
        try {
            mailProcessingRecord.setByteReceivedTotal(message.getSize());
    
            mailProcessingRecord.setMailId(id);
            mailProcessingRecord.setSubject(message.getSubject());
    
            mailProcessingRecord.setTimeFetchEnd(System.currentTimeMillis());
    
        } catch (MessagingException e) {
            log.info(queue + ": failed to process mail. remains on server");
            return;
        } finally {
            MailProcessingRecord matchedAndMergedRecord = results.matchMailRecord(mailProcessingRecord);
            if (matchedAndMergedRecord != null) {
                MailMatchingUtils.validateMail(message, matchedAndMergedRecord);
                results.recordValidatedMatch(matchedAndMergedRecord);
            }
        }
    
        dismissMessage();
    }

    /** 
     * mandatory override to make the message available
     */
    protected MimeMessage loadMessage() throws Exception {
        return null;
    }

    /**
     * optional override to delete the message.
     */
    protected void dismissMessage() throws Exception {
        ; // empty body
    }
    
    private MailProcessingRecord prepareRecord() {
        MailProcessingRecord mailProcessingRecord = new MailProcessingRecord();
        mailProcessingRecord.setReceivingQueue(queue);
        mailProcessingRecord.setTimeFetchStart(System.currentTimeMillis());
        return mailProcessingRecord;
    }
}
