package be.iminds.ilabt.jfed.util;

import org.apache.http.HttpHost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
 * SocksProxyHelper:
 *   uses some deprecated classes -> SOCKS proxy support is not an important feature, so not important if it breaks.
 */
public class SocksProxyHelper {

    public static class SOCKSConnectionSocketFactory implements ConnectionSocketFactory {

        public SOCKSConnectionSocketFactory() {
        }

        public Socket createSocket(final HttpContext context) throws IOException {
            int socksPort = 10801;
            if (System.getProperty("socksProxyPort") != null)
                socksPort = Integer.parseInt(System.getProperty("socksProxyPort"));

            InetSocketAddress socksaddr = new InetSocketAddress(System.getProperty("socksProxyHost"), socksPort);
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
            return new Socket(proxy);
        }
        public Socket connectSocket(
                final int connectTimeout,
                final Socket socket,
                final HttpHost host,
                final InetSocketAddress remoteAddress,
                final InetSocketAddress localAddress,
                final HttpContext context) throws IOException {
            Socket sock;
            if (socket != null) {
                sock = socket;
            } else {
                sock = createSocket(context);
            }
            if (localAddress != null) {
                sock.bind(localAddress);
            }
            try {
                sock.connect(remoteAddress, connectTimeout);
            } catch (SocketTimeoutException ex) {
                throw new ConnectTimeoutException(ex, host, remoteAddress.getAddress());
            }
            return sock;
        }
    }

}