package jmeetup;

import java.awt.*;
import java.io.*;
import java.net.*;

import gui.*;
import internet.*;


/**
 * A JMeetUp Client
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 */
public class Client
{
    private BufferedReader          in;
    private UDPMessageReceiver      messageReceiver;
    private PrintWriter             out;
    private Socket                  s;
    private String                  username;


    /**
     * Constructor
     */
    public Client(String username, String host, 
		  int tcpPort, int udpPort) throws IOException, 
                                                   SocketException
    {
       MessageWindow     messageWindow;


       this.username = username;

       s   = new Socket(host, tcpPort);
       out = new PrintWriter(s.getOutputStream());
       in  = new BufferedReader(
          new InputStreamReader(s.getInputStream()));


       // Send the login information
       send("login:"+username);
       send("port:"+udpPort);


       // Create the GUI components
       messageWindow = new MessageWindow();


       // Start the pieces
       messageReceiver = new UDPMessageReceiver(udpPort);
       messageReceiver.addMessageListener(messageWindow);
       messageReceiver.start();       
       processCommands();
       
       // Stop the pieces
       System.out.print("Bye, ");       
       messageReceiver.stop();
       messageWindow.setVisible(false);
       messageWindow.dispose();       
       System.out.print("bye...");       
    }



    /**
     * Read commands from the console, send them to the server, and
     * print the responses
     */
    private void processCommands()
    {
       BufferedReader  cin;
       String          line;

       cin = new BufferedReader(
          new InputStreamReader(System.in));

       try 
       {
          while ((line=cin.readLine()) != null) 
          {
             send(line);
             line = receive();
             System.out.println(line.replaceAll("<BR/>","\n")+"\n");
          }
          send("logout:"+username);
       } 
       catch (IOException ioe) 
       {
          ioe.printStackTrace();
       }
    }


    /**
     * Receive a line of text
     *
     * @return   The text
     */
    private String receive()
    {
       String   line;


       line = null;
       try 
       {
          line = in.readLine();
       }
       catch (IOException ioe) 
       {
          // Ignore it
       }

       return line;
    }


    /**
     * Send a line of text
     *
     * @param text   The text to send
     */
    private void send(String text)
    {
       out.println(text);
       out.flush();
    }
}
