package be.demmel.jgws.rmi;

import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum RmiRegistry {

    INSTANCE;
    private Logger logger = LoggerFactory.getLogger(RmiRegistry.class);
    private Registry registry;
    private URI uri;

    public void start(URI rmiUri) throws RemoteException, MalformedURLException {
        if (registry != null) {
            logger.info("RMI registry already up, ignoring startup request.");
            return;
        }

        if (rmiUri == null) {
            logger.warn("RMI Registry URI cannot be null, ignoring startup request.");
            return;
        }

        // Set URI
        this.uri = rmiUri;

        // Startup a RMI registry bound on the loopback only.
        // We don't use an external registry because:
        // 1. it can't listen on loopback only (we don't need this, but still :)
        // 2. it can't locate classes not defined in its classpath without poviding HTTP access to them (RMI was first designed for applets...)
        registry = LocateRegistry.createRegistry(uri.getPort(), new RMIClientSocketFactory() {

            // This creates the actual socket when a client connects to the RMI server
            @Override
            public Socket createSocket(String host, int port) throws IOException {
                InetAddress addr = InetAddress.getByName(host);
                // In order to restrict access to this RMI server by IP, it can be done here
//                    if (addr.equals(InetAddress.getLocalHost())) {
//                        return new Socket(addr, port);
//                    } else {
//                        throw new IOException("remote socket bind forbidden.");
//                    }
                return new Socket(addr, port);
            }
            // This creates the socket that listens for new connections
        }, new RMIServerSocketFactory() {

            @Override
            public ServerSocket createServerSocket(int port) throws IOException {
                //return new ServerSocket(port, 0, InetAddress.getByName("127.0.0.1"));
                return new ServerSocket(port);
            }
        });
    }

    // Binds a remote object to this RMI server
    public void bind(java.rmi.Remote remoteObject) throws RemoteException, MalformedURLException {
        Naming.rebind(uri.toASCIIString(), remoteObject);
    }
}
