/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package org.apache.james.transport.matchers;

import org.apache.mailet.GenericMatcher;
import org.apache.mailet.Mail;

import javax.mail.internet.MimeMessage;
import java.util.Collection;
import java.util.StringTokenizer;

/**
 *
 * @author  Marcus Labib Iskander
 * @version 1.0.0, 04/07/2002
 */

public class HeaderSmallerThan extends GenericMatcher {

    private String headerName;
    private int value;

    public void init() throws javax.mail.MessagingException {
        value = -1;
        String valueStr = null;
        StringTokenizer st = new StringTokenizer(getCondition(), ",", false);
        if (st.hasMoreTokens()) {
            headerName = st.nextToken();
            if (st.hasMoreTokens()) {
                valueStr = st.nextToken();
                try {
                    value = Integer.parseInt(valueStr);
                } catch (NumberFormatException nfe) {
                    value = -2;
                }
            }
        }
        if (st.hasMoreTokens()) {
            throw new IllegalArgumentException("surplus token '"+st.nextToken()+"' found!");
        } else if (headerName == null || headerName.length()==0) {
            throw new IllegalArgumentException("headerName must not be null or empty!");
        } else if (value==-1) {
            throw new IllegalArgumentException("upper limit of header value not found!");
        } else if (value==-2) {
            throw new IllegalArgumentException("can not parse 2nd token as a number: '"+valueStr+"'!");
        }   
    }

    public Collection match(Mail mail) throws javax.mail.MessagingException {
        MimeMessage mm = mail.getMessage();
        String header = mm.getHeader(headerName,null);
        int headerValue = 0;
        if (header != null) {
            try {
                headerValue = Math.max(0,Integer.parseInt(header));
            } catch (NumberFormatException nfe) {
                headerValue = 0;
            }
        }
        if (headerValue<value) {
            return mail.getRecipients();
        }
        return null;
    }
}

