/* 
 * In is a thread object that waits for people to connect.  It maintains a server socket, and 
 * when someone connects to it, it creates a new instance of the Connection object and then 
 * calls the connect() function.  The Connection instance is stored in the Network array.
 */

import java.io.*;
import java.util.*;
import java.net.*;
import java.util.*;
import java.lang.*;
import javax.swing.*;
import Connection;

// wait for clients to connect thread	
public class In extends Thread {    
    
    Network net;

    /* constructor.  port is the port the user's program is listening to. */
    public In(Network Net) {
	net = Net;
    }
    
    /* every thread has a run method . . . */
    public void run() 
    {
	/* for receiving messages via datagram */
	byte[] buffer = new byte[5096];

	try
	    {
		// open up a listen socket
		ServerSocket listen = new ServerSocket(net.get_listenPort());		  
				 		
		while (true)
		    {
			/* accept new clients */
			System.out.print("Waiting . . . ");
			Socket a = listen.accept();
			System.out.println("accepted.");

			/* receive port, hostname, username from connector */
			DatagramSocket dsocket = new DatagramSocket((int) net.get_myPort());
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			
			/* get the username */
			int len = packet.getLength();
			dsocket.receive(packet);
			String username = new String(buffer, 0, len);
			System.out.println(username);
			
			/* get the port */
			len = packet.getLength();
			dsocket.receive(packet);
			String port = new String(buffer, 0, len);
			System.out.println(port);
			
			/* get the address */
			String address = packet.getAddress().getHostName();
			System.out.println(address);

			dsocket.close();

			/* make the connection automatically */
			Connection newConn = new Connection(net);
			newConn.assign_name(username);
			newConn.assign_port(Integer.parseInt(port));
			newConn.assign_hostName(address);
			
			try {
			    Socket b = newConn.connect();
			    newConn.assign_connection(b);
			    net.add(newConn);
			    throw new IOException("Could not add new connection\n");
			}
			catch(IOException e) {
			    System.out.println("Unable to make automatic connection; try manual.");
			};
			    
		    } // end while
	    }
	// end try
	catch(IOException e)
	    {
		System.out.println("Unable to initialize listen port.");
	    };
		
    }
};

