/** 
 * 
 * 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.transport.composite;

import org.codehaus.activemq.io.WireFormat;
import org.codehaus.activemq.transport.TransportChannel;
import org.codehaus.activemq.transport.TransportChannelFactory;
import org.codehaus.activemq.transport.TransportChannelFactorySupport;
import org.codehaus.activemq.transport.vm.VmTransportChannel;
import org.codehaus.activemq.util.JMSExceptionHelper;

import javax.jms.JMSException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * A Composite implementation of a TransportChannelFactory
 *
 * @version $Revision: 1.4 $
 */
public class CompositeTransportChannelFactory extends TransportChannelFactorySupport {
    private String separator = ",";

    public TransportChannel create(WireFormat wireFormat, URI remoteLocation) throws JMSException {
        try {
            TransportChannel result = new CompositeTransportChannel(wireFormat, parseURIs(remoteLocation));
            return populateProperties(result, remoteLocation);
        }
        catch (URISyntaxException e) {
            throw JMSExceptionHelper.newJMSException("Can't parse list of URIs for: " + remoteLocation + ". Reason: " + e, e);
        }
    }

    public TransportChannel create(WireFormat wireFormat, URI remoteLocation, URI localLocation) throws JMSException {
        return create(wireFormat, remoteLocation);
    }

    public boolean requiresEmbeddedBroker() {
        return false;
    }

    protected List parseURIs(URI uri) throws URISyntaxException {
        String text = uri.getSchemeSpecificPart();
        List uris = new ArrayList();
        StringTokenizer iter = new StringTokenizer(text, separator);
        while (iter.hasMoreTokens()) {
            String child = stripLeadingSlashes(iter.nextToken().trim());
            uris.add(new URI(child));
        }
        return randomizeURIs(uris);
    }

    protected String stripLeadingSlashes(String text) {
        int idx = 0;
        while (idx < text.length() && text.charAt(idx) == '/') {
            idx++;
        }
        if (idx > 0) {
            return text.substring(idx);
        }
        return text;
    }


    protected List randomizeURIs(List uris) {
        return uris;
    }
}