/** 
 * 
 * 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.activemq.transport;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.jms.JMSException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import EDU.oswego.cs.dl.util.concurrent.CopyOnWriteArrayList;

/**
 * An abstract base class useful for implementation inheritence
 * 
 * @version $Revision: 1.1.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 CopyOnWriteArrayList();

    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();) {
            WeakReference channelRef = (WeakReference) iter.next();            
            TransportChannel channel = (TransportChannel) channelRef.get();
            if( channel!=null )
                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;
    }

    /**
     * Add a channel
     * @param channel
     */
    public 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(new WeakReference(channel));
        }
    }
    
    /**
     * remove a channel
     * @param channel
     */
    public synchronized void removeClient(TransportChannel channel){
        for (Iterator iter = channels.iterator();iter.hasNext();) {
            WeakReference channelRef = (WeakReference) iter.next();            
            TransportChannel c = (TransportChannel) channelRef.get();
            if( c!=null && c.equals(channel)){
                channels.remove(channelRef);
                break;
            }
        }
    }

    protected String resolveHostName(String hostName) {
        String result = hostName;
        try {
            //hostname can be null for vm:// protocol ...
            if (hostName != null && (hostName.equalsIgnoreCase("localhost") || hostName.equals("127.0.0.1"))) {
                result = InetAddress.getLocalHost().getHostName();
            }
        }
        catch (UnknownHostException e) {
            log.debug("failed to resolve hostname", e);
        }
        return result;
    }
}