/** 
 * 
 * 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;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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

/**
 * An abstract base class useful for implementation inheritence
 *
 * @version $Revision: 1.1 $
 */
public abstract class TransportServerChannelSupport implements TransportServerChannel {

    private static final Log log = LogFactory.getLog(TransportServerChannelSupport.class);

    private String url;
    private TransportChannelListener transportChannelListener;
    private List channels = new ArrayList();

    public TransportServerChannelSupport(URI url) {
        this(url.toString());
    }

    public TransportServerChannelSupport(String url) {
        this.url = url;
    }

    public void start() throws JMSException {
        if (transportChannelListener == null) {
            throw new JMSException("Must have a TransportChannelListener attached!");
        }
    }

    public synchronized void stop() throws JMSException {
        for (Iterator iter = channels.iterator(); iter.hasNext();) {
            TransportChannel channel = (TransportChannel) iter.next();
            channel.stop();
        }
    }

    public TransportChannelListener getTransportChannelListener() {
        return transportChannelListener;
    }

    public void setTransportChannelListener(TransportChannelListener listener) {
        this.transportChannelListener = listener;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    protected synchronized void addClient(TransportChannel channel) {
        if (transportChannelListener == null) {
            log.warn("No listener attached, cannot add channel: " + channel);
        }
        else {
            transportChannelListener.addClient(channel);
            channel.setTransportChannelListener(transportChannelListener);
            channels.add(channel);
        }
    }
}