package com.orbekk.same;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.orbekk.protobuf.RpcChannel;

public class ConnectionManagerImpl implements ConnectionManager {
    private int connectionTimeout;
    private int readTimeout;
    private ConcurrentMap<String, Future<RpcChannel>> channels =
            new ConcurrentHashMap<String, Future<RpcChannel>>();
    
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * @param connectionTimout Timeout for establishing connection in milliseconds.
     * @param readTimeout Timeout for waiting for answer in milliseconds.
     */
    public ConnectionManagerImpl(int connectionTimout, int readTimeout) {
        this.connectionTimeout = connectionTimout;
        this.readTimeout = readTimeout;
    }

    private RpcChannel getChannel(String location) {
        Future<RpcChannel> channel = channels.get(location);
        if (channel == null) {
            final String hostname = location.split(":")[0];
            final int port = Integer.valueOf(location.split(":")[1]);
            Callable<RpcChannel> channelFactory =
                    new Callable<RpcChannel>() {
                @Override public RpcChannel call() {
                    try {
                        return RpcChannel.create(hostname, port);
                    } catch (UnknownHostException e) {
                        logger.error("Could not connect: ", e);
                        return null;
                    } catch (IOException e) {
                        logger.error("Could not connect: ", e);
                        return null;
                    }
                }
            };
            FutureTask<RpcChannel> task =
                    new FutureTask<RpcChannel>(channelFactory);
            channel = channels.putIfAbsent(location, task);
            if (channel == null) {
                task.run();
                channel = task;
            }
        }
        try {
            return channel.get();
        } catch (ExecutionException e) {
            logger.error("Could not connect: ", e);
            return null;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return null;
        }
    }

    @Override
    public Services.Master getMaster0(String location) {
        RpcChannel channel = getChannel(location);
        if (channel != null) {
            return Services.Master.newStub(channel);
        } else {
            return null;
        }
    }
    
    @Override
    public Services.Client getClient0(String location) {
        RpcChannel channel = getChannel(location);
        if (channel != null) {
            return Services.Client.newStub(channel);
        } else {
            return null;
        }
    }
    
    @Override
    public Services.Directory getDirectory(String location) {
        RpcChannel channel = getChannel(location);
        if (channel != null) {
            return Services.Directory.newStub(channel);
        } else {
            return null;
        }
    }
    
    @Override
    public Services.Paxos getPaxos0(String location) {
        RpcChannel channel = getChannel(location);
        if (channel != null) {
            return Services.Paxos.newStub(channel);
        } else {
            return null;
        }
    }
}

@@ -1237,196 +1237,772 @@
 ate 
-RpcChannel getChannel(String location) %7B%0A        Future%3CRpcChannel%3E channel = channels.get(location);%0A        if (channel == null) %7B%0A            final String hostname = location.split(%22:%22)
+boolean isValidLocation(String location) %7B%0A        String%5B%5D args = location.split(%22:%22);%0A        if (args.length != 2) %7B%0A            logger.error(%22Invalid location: %22 + location);%0A            return false;%0A        %7D%0A        try %7B%0A            Integer.valueOf(args%5B1%5D);%0A        %7D catch (IllegalArgumentException e) %7B%0A            logger.error(%22Invalid location: %22 + location);%0A            return false;%0A        %7D%0A        return true;%0A    %7D%0A    %0A    private RpcChannel getChannel(String location) %7B%0A        Future%3CRpcChannel%3E channel = channels.get(location);%0A        if (channel == null) %7B%0A            if (!isValidLocation(location)) %7B%0A                return null;%0A            %7D%0A            String%5B%5D args = location.split(%22:%22);%0A            final String hostname = args
 %5B0%5D;
@@ -2051,32 +2051,30 @@
 eOf(
-location.split(%22:%22)%5B1%5D);
+args%5B1%5D);%0A            
 %0A   

Fix error handling in ConnectionManagerImpl.