package oracle.forms.fd;

import java.io.*;
import java.net.*;

/*
 * a class to manage a socket server
 */
public class ChatServer extends Thread
{
  private static final int WAIT_FOR_CLIENT = 0 ;
  private static final int WAIT_FOR_ANSWER = 1 ;
  private ServerSocket sock;
  private int state = WAIT_FOR_CLIENT;
  
  public ChatServer( int iPortNumber )
  {
    super("SocketServer") ;
    try
    {
      sock = new ServerSocket(iPortNumber);
      System.out.println("ServerSocket is running");
      ChatClient.bOk = true ;
    } catch (IOException ioe) 
    {
      System.err.println("Error : unable to create socket");
      ChatClient.bOk = false ;
    }
  }
  
  public void run()
  {
    Socket client = null ;
    while (true)
    {
      if (sock == null)
         return ;
      try 
      {
        client = sock.accept();
      } catch (IOException ioe) 
      {
        System.err.println("Error : unbale to connect the client");
        return ;
      }
      try
      {
        InputStreamReader isr = new InputStreamReader(client.getInputStream()) ;
        BufferedReader is = new BufferedReader(isr);
        PrintWriter os = new PrintWriter(new BufferedOutputStream(client.getOutputStream()),false);
        String outLine;
        String inLine="";
        
        outLine = getClientString(null);
        os.println(outLine);
        os.flush();
        
        while(true)
        {
          try{
            inLine = is.readLine();
          if (inLine.length() > 0)
          {
             outLine = getClientString(inLine);
             if( outLine != null )
             {
               System.out.println("outLine="+outLine);
               ChatClient.sMessage = outLine ;
               ChatClient.bMsg = true ;
             }
          }
          else
             outLine = getClientString("");
          os.println(outLine);
          os.flush();
          if( outLine.equals("Bye."))
             break ;
          }
          catch(Exception ex)
          {
            break ;
          }             
          try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {;}             
        }
        os.close();
        is.close();
      } catch (Exception e) 
      {
        System.err.println("Error : "+e);
        e.printStackTrace();
      }
    }
  }
  
  // get the input from the client  
  String getClientString( String s)
  {
    String outStr = null ;
    switch (state)
    {
       case WAIT_FOR_CLIENT:
          outStr = "Server is ready, waiting for input\r\n enter Bye. to quit" ;
          state = WAIT_FOR_ANSWER ;
          break;
       case WAIT_FOR_ANSWER:
          outStr = s ;
          break ;     
    }
    return outStr ;
  }
  
}

