/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed 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.codehaus.activemq.filter;

import org.codehaus.activemq.message.ActiveMQDestination;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;


/**
 * Represents a filter which only operates on Destinations
 *
 * @version $Revision: 1.2 $
 */
public abstract class DestinationFilter implements Filter {
    public static final String ANY_DESCENDENT = ">";
    public static final String ANY_CHILD = "*";

    public boolean matches(Message message) throws JMSException {
        return matches(message.getJMSDestination());
    }

    public abstract boolean matches(Destination destination);

    public static DestinationFilter parseFilter(Destination destination) {
        if (destination instanceof ActiveMQDestination) {
            ActiveMQDestination activeDestination = (ActiveMQDestination) destination;
            if (activeDestination.isComposite()) {
                return new CompositeDestinationFilter(activeDestination);
            }
        }
        String[] paths = DestinationPath.getDestinationPaths(destination);
        int idx = paths.length - 1;
        if (idx >= 0) {
            String lastPath = paths[idx];
            if (lastPath.equals(ANY_DESCENDENT)) {
                return new PrefixDestinationFilter(paths);
            }
            else {
                while (idx >= 0) {
                    lastPath = paths[idx--];
                    if (lastPath.equals(ANY_CHILD)) {
                        return new WildcardDestinationFilter(paths);
                    }
                }
            }
        }

        // if none of the paths contain a wildcard then use equality
        return new SimpleDestinationFilter(destination);
    }
}
