import java.io.*;
import java.net.*;

class SocketDaemon3 extends Thread {

    HouseDaemon3 snitch = new HouseDaemon3();
    Socket connection;
    DataOutputStream output = null;
    DataInputStream input = null;
    boolean go = true;
    
//*********************************
    SocketDaemon3 ( HouseDaemon3 hd, Socket s ) {	// constructor method
	snitch = hd;
	connection = s;
	runServer();
    }

//*********************************
    public void run() {
	System.out.println( "thread running: " + currentThread() );
	while ( go ) {
	    try{
		receiveData();
		sleep( 20 );
	    } catch( InterruptedException ioe ) {
		go = false;
	    }
	}
    }

//*********************************
    public void runServer(){
	
	try{
	    
	    output = new DataOutputStream( connection.getOutputStream() );
	    System.out.println( currentThread()
				+ " has established output connection with client:"
				+ connection.getInetAddress().getHostName() );
	    
	    input = new DataInputStream( connection.getInputStream() );
	    System.out.println( currentThread()
			       + " has established input connection with client:"
			       + connection.getInetAddress().getHostName() );
	} catch( IOException ioe ) {
	    System.out.println( currentThread()
				+ " has no connection: closing socket" );
	    go = false;
	}
	
    }

//*********************************
    public void receiveData() {
	try{
	    // get data from client
	    int  x = input.readInt();
	    int y = input.readInt();
	    int index = input.readInt();

	    // broadcast it to all SocketDaemons
	    boolean response = snitch.broadcast( x, y, index );
	    if ( !response )  go = false; 
 
	} catch( IOException ioe ) {
	    System.out.println( "thread has no connection" );
	    go = false;
	}
	
    }


//*********************************
    public boolean tell( int x, int y, int index ) {
	// send data to client
	try{
	    output.writeInt( x );
	    output.writeInt( y );
	    output.writeInt( index );
	    return true;
	} catch( IOException ioe ) {
	    System.out.println( "thread has no connection" );
	    go = false;
	    return false;
	}
    }

//*********************************
}
