/*
 * same as previous. endless loop or server disconnection bug fixed 
 * 
 *  */

package client;

/**
 *
 * @author Paty
 */

    
    
import java.net.*;
import java.io.*;
import java.applet.*;
import java.awt.*;
import javax.swing.*;



public class TCPClient extends Applet
{  /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Socket socket              = null;
	//private DataInputStream  console   = null;
	private DataOutputStream streamOut = null;
	private TCPClientThread client    = null;
	private TextArea  display = new TextArea();
	private TextField input   = new TextField();
	private Button    send    = new Button("Send"), connect = new Button("Connect"),
                     quit    = new Button("Bye");
	private String    serverName;// = "localhost";
	private int       serverPort;// = 4444;
	private String nickname = "";

   public void init() { 
      Panel keys = new Panel();
      keys.setLayout(new GridLayout(1,2));
      keys.add(quit); 
      keys.add(connect);
      Panel south = new Panel();
      south.setLayout(new BorderLayout());
      south.add("West", keys);
      south.add("Center", input);
      south.add("East", send);
      Label title = new Label("Simple Chat Client Applet", Label.CENTER);
      title.setFont(new Font("Helvetica", Font.BOLD, 14));
      setLayout(new BorderLayout());
      add("North", title);
      add("Center", display);
      add("South",  south);
      quit.setEnabled(false);
      send.setEnabled(false);
      }
   
   
   public boolean action(Event e, Object o) {  
       if (e.target == quit) {
           input.setText("/exit");
           quit.setEnabled(false);
           send.setEnabled(false);
           connect.setEnabled(false);
           handle("/exit");
       } else if (e.target == connect) {
           getParameters();
           connect(serverName, serverPort);
       } else if (e.target == send) { 
           send();
           input.requestFocus(); 
       }
      return true;
   }
   
   
   public void connect(String serverName, int serverPort) {
       println("Establishing connection. Please wait ...");
      try {
         socket = new Socket(serverName, serverPort);
         println("Connected: " + socket);
         open();
         send.setEnabled(true);
         connect.setEnabled(false);
         quit.setEnabled(true);
         join();
      } catch(UnknownHostException uhe) {
          println("Host unknown: " + uhe.getMessage()); 
          getParameters(); 
      } catch(IOException ioe) { 
          println("Unexpected exception: " + ioe.getMessage()); 
          getParameters(); 
      }
   }
   
   private void join() {
       try {
           streamOut.writeUTF(nickname + " joined the chat!"); streamOut.flush(); input.setText("");
       } catch(IOException ioe) { 
           println("Sending error: " + ioe.getMessage()); 
           println("Server may be down at the time, program gets terminated.");
           handle("/exit");
       } 
   }
   
   private void leave() {
       try {
           streamOut.writeUTF(nickname + " left the chat."); streamOut.flush(); input.setText("");
       } catch(IOException ioe) { 
           println("Sending error: " + ioe.getMessage()); 
           println("Server may be down at the time, program gets terminated.");
       } 
   }
   
   
   private void send() {
       try {
           streamOut.writeUTF(nickname + ": " + input.getText()); streamOut.flush(); input.setText("");
       } catch(IOException ioe) { 
           println("Sending error: " + ioe.getMessage()); 
           println("Server may be down at the time, program gets terminated.");
           handle("/exit");
       } 
   }
   
   
   public void handle(String msg) {
       if (msg.equals("/exit")) {
           println("Good bye. You can now close the window ...");  
           quit.setEnabled(false);
           send.setEnabled(false);
           leave();
           close(); 
       } else println(msg);
   }
   
   public void open() {
       try {
           streamOut = new DataOutputStream(socket.getOutputStream());
           client = new TCPClientThread(this, socket); 
       } catch(IOException ioe) {
           println("Error opening output stream: " + ioe);
       }
   }
   
   public void close() {
       try {
           if (streamOut != null)
               streamOut.close();
         if (socket    != null)
             socket.close(); 
       } catch(IOException ioe) {
           println("Error closing ..."); 
       }
      client.stopClientThread(); 
   }
   
   private void println(String msg) {
       display.append(msg + "\n");
   }
   
   public void getParameters() {
      
      
        serverName = JOptionPane.showInputDialog(null, "Enter server ip : ");
        System.out.println(serverName);
       
        nickname = JOptionPane.showInputDialog(null, "Enter nickname : ");
       
      
        serverPort = 7896; 
   }
   
}
    

