// MuDispatcher.java
// dispatch a client's message to other clients
import java.net.*;
import java.io.*;
import java.util.*;

class MuDispatcher extends Thread {
   DataInputStream in = null;
   DataOutputStream out = null;
   Vector clients;

   MuDispatcher(Socket s, Vector c, int id){
      super("MuDispatcher");

      clients = c;

      try {
         // create input/output streams from/to client
         in = new DataInputStream(s.getInputStream());
         out = new DataOutputStream(s.getOutputStream());

         out.writeInt(id); // send id to client

         this.start();       // start this thread
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   public void run(){
      int id;
      int command;
      float x=0f, y=0f, z=0f, r=0f;

      try{
         while(true){
	// read message from a client
	id = in.readInt();
	command = in.readInt();
	x = in.readFloat();
	y = in.readFloat();
	z = in.readFloat();
	if(MuProtocol.ROTATION == command){ r = in.readFloat();}

	// dispatch message to other clients
	for(int i = 0; i < clients.size(); i++){
	   if(i != id){
	      if(MuProtocol.ROTATION == command){
	         ((MuDispatcher)clients.elementAt(i)).output(id, command, x, y, z, r);
	      }else{
	         ((MuDispatcher)clients.elementAt(i)).output(id, command, x, y, z);
	      }
	   } // else{
	      // System.out.println("dispatch client " + i +    
	      //	          ": (" + x + "," + y + "," + z + ") to others...");	
	      // }
	}
         }
      }catch (IOException e){
         e.printStackTrace();
      }
   }

   // send message to client
   public synchronized void output(int id, int command, float x, float y, float z){
      try{
         out.writeInt(id);
         out.writeInt(command);
         out.writeFloat(x);
         out.writeFloat(y);
         out.writeFloat(z);
      }catch (IOException e){
         e.printStackTrace();
      }
   }

   // send message to client
   public synchronized void output(int id, int command, float x, float y, float z, float r){
      try{
         out.writeInt(id);
         out.writeInt(command);
         out.writeFloat(x);
         out.writeFloat(y);
         out.writeFloat(z);
         out.writeFloat(r);
      }catch (IOException e){
         e.printStackTrace();
      }
   }
}
