package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;

public class TcpConnector implements Connector {
	private Socket socket;
	private String hostname;
	private int port;

	private DataInputStream inStream;
	private DataOutputStream outStream;

	public TcpConnector(Socket s) {
		if(s == null) throw new NullPointerException();
		socket = s;
	}
	public TcpConnector(String hostname, int port) throws UnknownHostException, IOException {
		socket = new Socket(hostname, port);
		this.hostname = hostname;
		this.port = port;
	}

	public void establishConnection() throws IOException {
		inStream = new DataInputStream(socket.getInputStream());
		outStream = new DataOutputStream(socket.getOutputStream());
	}	

	public void closeConnection() throws IOException {
		socket.close();
	}

	public DataInputStream getInputStream() { return inStream; }
	public DataOutputStream getOutputStream() { return outStream; }
	
	@Override
	public String toString() {
		String hname = hostname!=null ? hostname : socket.getInetAddress().toString();
		int p = port==0 ? port : socket.getPort();
		if(socket.isConnected()) {
			return "Currently connected to " + hname + " on port " + p;
		} else {
			return "Currently not connected.";
		}
	}	
	
//	public void setTimeout(int timeout) throws IOException {
//		socket.setSoTimeout(timeout);
//	}
}
