/**
 * 
 * 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 org.codehaus.activemq.ConfigurationException;
import org.codehaus.activemq.io.WireFormat;
import org.codehaus.activemq.transport.reliable.ReliableTransportChannel;
import org.codehaus.activemq.util.Callback;
import org.codehaus.activemq.util.ExceptionTemplate;
import org.codehaus.activemq.util.MapHelper;

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

/**
 * A {@link ReliableTransportChannel} which uses a {@link DiscoveryAgent} to discover remote broker
 * instances and dynamically connect to them.
 *
 * @version $Revision: 1.3 $
 */
public class DiscoveryTransportChannel extends ReliableTransportChannel implements DiscoveryListener {
    private static final Log log = LogFactory.getLog(DiscoveryTransportChannel.class);


    private DiscoveryAgent discoveryAgent;
    private String remoteUserName;
    private String remotePassword;


    public DiscoveryTransportChannel(WireFormat wireFormat, DiscoveryAgent discoveryAgent) {
        super(wireFormat);
        this.discoveryAgent = discoveryAgent;
    }

    public void start() throws JMSException {
        if (discoveryAgent == null) {
            throw new ConfigurationException("Must be configured with a discoveryAgent property");
        }

        // lets pass into the agent the broker name and connection details
        discoveryAgent.addDiscoveryListener(this);
        discoveryAgent.start();

        super.start();
    }

    public void stop() {
        ExceptionTemplate template = new ExceptionTemplate();
        template.run(new Callback() {
            public void execute() throws Throwable {
                discoveryAgent.stop();
            }
        });
        template.run(new Callback() {
            public void execute() throws Throwable {
                DiscoveryTransportChannel.super.stop();
            }
        });
        Throwable e = template.getFirstException();
        log.warn("Failed to stop the transport channel cleanly due to: " + e, e);
    }


    public synchronized void addService(DiscoveryEvent event) {
        Map details = event.getServiceDetails();
        String url = MapHelper.getString(details, "connectURL");
        if (url != null) {
            try {
                URI uri = new URI(url);
                List urlList = getUris();
                if (!urlList.contains(uri)) {
                    log.info("Adding new broker connection URL: " + uri + " with details: " + details);

                    urlList.add(uri);
                }
            }
            catch (URISyntaxException e) {
                log.warn("Could not connect to remote URI: " + url + " due to bad URI syntax: " + e, e);
            }
        }
    }

    public synchronized void removeService(DiscoveryEvent event) {
        Map details = event.getServiceDetails();
        String url = MapHelper.getString(details, "connectURL");
        if (url != null) {
            try {
                URI uri = new URI(url);
                synchronized (this) {
                    List urlList = getUris();
                    if (urlList.remove(uri)) {
                        log.info("Removing broker connection URL: " + uri);
                    }
                }
            }
            catch (URISyntaxException e) {
                log.warn("Could not remove remote URI: " + url + " due to bad URI syntax: " + e, e);
            }
        }
    }

    // Properties
    //-------------------------------------------------------------------------
    public DiscoveryAgent getDiscoveryAgent() {
        return discoveryAgent;
    }

    public void setDiscoveryAgent(DiscoveryAgent discoveryAgent) {
        this.discoveryAgent = discoveryAgent;
    }


    public String getRemotePassword() {
        return remotePassword;
    }

    public void setRemotePassword(String remotePassword) {
        this.remotePassword = remotePassword;
    }

    public String getRemoteUserName() {
        return remoteUserName;
    }

    public void setRemoteUserName(String remoteUserName) {
        this.remoteUserName = remoteUserName;
    }

}
