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


public class PlayerServerHandler extends Thread
{
  private FBFServer server;
  private Socket clientSock;
  private BufferedReader in;
  private PrintWriter out;

  private int playerID;     // this player id is assigned by FBFServer


  public PlayerServerHandler(Socket s, FBFServer serv)
  {
    clientSock = s;
    server = serv;
    System.out.println("Player connection request");
    try {
      in  = new BufferedReader( 
			    new InputStreamReader( clientSock.getInputStream() ) );
      out = new PrintWriter( clientSock.getOutputStream(), true );  // autoflush
    }
    catch(Exception e)
    {  System.out.println(e);  }
  }


  public void run()
  /* Add this player to FBFServer array, get an ID, then 
     start processing client-side input
  */
  {
    playerID = server.addPlayer(this);
    if (playerID != -1) {    // -1 means adding the player was rejected
      sendMessage("ok " + playerID);
      System.out.println("ok " + playerID);  // tell player his/her playerID
      server.tellOther(playerID, "added " + playerID);

      processPlayerInput();

      server.removePlayer(playerID);   // remove player from server data
      server.tellOther(playerID, "removed " + playerID);    // tell others
    }
    else    // game is full
      sendMessage("full");

    try {     // close socket from player
      clientSock.close();
      System.out.println("Player " + playerID + " connection closed\n");
    }
    catch(Exception e)
    {  System.out.println(e);  }

  }  // end of run()


   private void processPlayerInput()
   /* Stop when the input stream closes (is null) or "disconnect" is sent.
      Otherwise pass the input to doRequest(). */
   {
     String line;
     boolean done = false;
     try {
       while (!done) {
         if((line = in.readLine()) == null)
           done = true;
         else {
            //System.out.println("Player " + playerID + " msg: " + line);
           if (line.trim().equals("disconnect"))
             done = true;
               //done = false;
           else
             server.tellOther(playerID,line);
             doRequest(line);
         }
       }
     }
     catch(IOException e)
     {  System.out.println("Player " + playerID + " closed the connection"); }
   }  // end of processPlayerInput()


  private void doRequest(String line)
  {	
      
    if (line.startsWith("try")) {
      try {
        if (server.enoughPlayers())
          System.out.println("mängijaid piisvalt");
        else
          sendMessage("liiga vähe mängijaid");
      }
      catch(NumberFormatException e)
      { System.out.println(e); } 
    }
    if (line.startsWith("random")) {
        randomizeBall();
        //System.out.println("töötab");
    	}
  }  // end of doRequest()

  private void randomizeBall()
  {
  	Random rnd = new Random();
  	boolean vert = rnd.nextBoolean();
  	boolean horiz = rnd.nextBoolean();
  	double xvel, yvel;
  	
  	if(vert)
  		yvel = 1;
  	else
  		yvel = -1;
  		
  	if(horiz){
  		xvel = 1;
  	}else{
  		xvel = -1;}
  	//System.out.println(playerID);
  	server.tellOther(1, "velocity "+xvel+" "+yvel);	
  	server.tellOther(2, "velocity "+xvel+" "+yvel);	
  	//ball.setVelocity(xvel, yvel);
  }
  synchronized public void sendMessage(String msg)
  // called by handler and top-level server
  { try {
        out.println(msg);
    }
    catch(Exception e)
    {  System.out.println("Handler for player " + playerID + "\n" + e);  }
  }  // end of sendMessage()


}  // end of PlayerServerHandler class
