/**
 * 
 * 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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.activemq.ConfigurationException;
import org.activemq.broker.BrokerContainer;
import org.activemq.util.MapHelper;
import org.activemq.util.URIHelper;
import EDU.oswego.cs.dl.util.concurrent.BoundedBuffer;
import EDU.oswego.cs.dl.util.concurrent.Executor;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
import javax.jms.JMSException;
import java.net.InetAddress;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * A {@link NetworkConnector}which uses discovery to find remote brokers to connect to
 * 
 * @version $Revision: 1.1.1.1 $
 */
public class DiscoveryNetworkConnector extends NetworkConnector implements DiscoveryListener {
    private static final Log log = LogFactory.getLog(DiscoveryNetworkConnector.class);
    private DiscoveryAgent discoveryAgent;
    private Map channelMap = new HashMap();

    public DiscoveryNetworkConnector(BrokerContainer brokerContainer) {
        super(brokerContainer);
    }

    public void start() throws JMSException {
        DiscoveryAgent discoveryAgent = getBrokerContainer().getDiscoveryAgent();
        if (discoveryAgent == null) {
            throw new ConfigurationException("Must be configured with a discoveryAgent property");
        }
        discoveryAgent.addDiscoveryListener(this);
        super.start();
    }

    public void addService(final DiscoveryEvent event) {
        try {
            Map details = event.getServiceDetails();
            if (!getLocalBrokerName().equals(details.get("brokerName"))) {
                String url = MapHelper.getString(details, "connectURL");
                if (url != null) {
                    addChannel(url, details);
                }
            }
        }
        catch (Exception e) {
            log.warn("Add service failed", e);
        }
    }

    public void removeService(final DiscoveryEvent event) {
        try {
            Map details = event.getServiceDetails();
            if (!getLocalBrokerName().equals(details.get("brokerName"))) {
                String url = MapHelper.getString(details, "connectURL");
                if (url != null) {
                    removeChannel(url, details);
                }
            }
        }
        catch (Exception e) {
            log.warn("remove service failed", e);
        }
    }

    // Implementation methods
    //-------------------------------------------------------------------------
    protected synchronized void addChannel(String url, Map details) {
        NetworkChannel channel = (NetworkChannel) channelMap.get(url);
        if (channel == null) {
            try {
                final String RELIABLE = "reliable:";
            String urlStr = url.toLowerCase().trim();
            if (urlStr.startsWith(RELIABLE)){
                urlStr = urlStr.substring(RELIABLE.length());
            }
            String realURL = url;
            URI temp = new URI(urlStr);
            String hostName = temp.getHost();
            if (hostName != null && InetAddress.getByName(hostName).equals(InetAddress.getLocalHost())){
                temp = new URI(temp.getScheme(), temp.getUserInfo(), "localhost", temp.getPort(),
                        temp.getPath(), temp.getQuery(), temp.getFragment());
                realURL = temp.toString();
            }
            channel = createNetworkChannel(realURL);
            channel.setUri(realURL);
    
            log.info(getLocalBrokerName() + ": Adding new NeworkChannel on: " + url + "{resolved=" + realURL +"} with details: " + details);
            channel.start();
            channelMap.put(url, channel);
            }catch(Exception e){
                log.error("Failed to add NetworkChannel",e);
            }
        }
    }

    protected synchronized void removeChannel(String url, Map details) {
        NetworkChannel channel = (NetworkChannel) channelMap.remove(url);
        if (channel != null) {
            log.info(getLocalBrokerName() + ": Removing NeworkChannel: " + channel);
            try {
                channel.stop();
            }
            catch (JMSException e) {
                log.info("Failed to stop channel: " + channel + ". Reason: " + e, e);
            }
        }
    }

    protected String getLocalBrokerName() {
        return getBrokerContainer().getBroker().getBrokerName();
    }
}