package org.ourfilesystem.com;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SimpleConnector implements OFSConnector {

	private boolean UseProxy;
	private int ProxyPort;
	private String ProxyAddr;
	
	public SimpleConnector(boolean useproxy, String proxyaddr, int port) {
		UseProxy = useproxy;
		ProxyAddr = proxyaddr;
		ProxyPort = port;
	}
	
	@Override
	public OFSSocket connect(String location) throws IOException {
		Pattern p = Pattern.compile("(\\S+):(\\d+)");
		Matcher m = p.matcher(location);
		if (m.find()) {
			String addr = m.group(1);
			int port = Integer.valueOf(m.group(2));
			if (UseProxy) {
				InetSocketAddress address = InetSocketAddress.createUnresolved(ProxyAddr, ProxyPort);
				Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
				Socket s = new Socket(proxy);
				InetSocketAddress c = InetSocketAddress.createUnresolved(addr, port);
				s.connect(c, 0);
				return new SimpleSocket(s);
			}
			else {
				return new SimpleSocket(new Socket(addr, port));
			}
		}
		throw new IOException("Invalid address " + location);
	}

	public boolean isUseProxy() {
		return UseProxy;
	}

	public void setUseProxy(boolean useProxy) {
		UseProxy = useProxy;
	}

	public int getProxyPort() {
		return ProxyPort;
	}

	public void setProxyPort(int proxyPort) {
		ProxyPort = proxyPort;
	}

	public String getProxyAddr() {
		return ProxyAddr;
	}

	public void setProxyAddr(String proxyAddr) {
		ProxyAddr = proxyAddr;
	}

}
