//From: Lin Se-Ying <sylin@csie.nctu.edu.tw>
//Date: Sat, 9 Jun 2001 14:32:40 +0000 (UTC)
//>   (5) 因為用 telnet 直接連此server 很難用, 打字時隨時會被message打斷行
//>       如果寫一個 client 就會覺得很好用
//>       用Java 寫一個 application program, 使得你打字的部份和大家聊天部份分開
//>       可以使用 TextArea, 當然是要能夠捲回去看的
//>       執行時可讓使用者指定 server 和 port
//>       第一個正確潑上來的加小考15分, 並可指定任一位同學加小考5分
//
//8917008 林仕盈 指定 8917010 郭達人
//
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client extends JFrame {
   private JTextField enter;
   private JTextArea display;
   private BufferedReader in;
   private PrintWriter out;

   String message = "";

   public Client()
   {
      super( "Client" );

      Container c = getContentPane();

      enter = new JTextField();
      enter.setEnabled( false );
      enter.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               sendData( e.getActionCommand() );
               enter.selectAll();
               enter.cut();
            }
         }
      );
      c.add( enter, BorderLayout.SOUTH );

      display = new JTextArea();
      display.setEditable(false);
      c.add( new JScrollPane( display ),
             BorderLayout.CENTER );

      setSize( 600, 450 );
      show();
   }

   public void runClient(InetAddress host,int port)
   {
      Socket client;
      InputStream t;
      try {
         // Step 1: Create a Socket to make connection.
         display.setText( "Attempting connection\n" );
         client = new Socket( host, port );
         display.append( "Connected to: " +
            client.getInetAddress().getHostName()+":"+ client.getPort() );

         // Step 2: Get the input and output streams.
         in = new BufferedReader(
                  new InputStreamReader(client.getInputStream()) );
         out = new PrintWriter(
                  new OutputStreamWriter(client.getOutputStream()), true );

         display.append( "\nGot I/O streams\n" );

         // Step 3: Process connection.
         enter.setEnabled( true );
         boolean quit=false;
         try {
            while( (message = in.readLine())!=null )
            {
               display.append( message+'\n' );
               display.setCaretPosition(
                  display.getText().length() );
            }
         }
         catch ( IOException cnfex ) {
            display.append("\nUnknown object type received" );
         }
         enter.setEnabled( false );
         display.append( "Closing connection.\n" );
         out.close();
         in.close();
         client.close();
      }
      catch ( EOFException eof ) {
         System.out.println( "Server terminated connection" );
      }
      catch ( IOException e ) {
         e.printStackTrace();
      }
   }

   private void sendData( String s )
   {
      message = s;
      if( s.length()==0)
         return ;
      out.println( s );
      display.append( s + "\n");
      out.flush();
   }

   public static void main( String args[] )
   {
      if ( args.length != 2 ) {
          System.out.println("Usage: java Client hostname port");
          System.exit(0);
      }
      int port = 0;
      System.out.println(args[0]);
      InetAddress host=null;
      try 
      {
         host = InetAddress.getByName( args[0] );
         port = Integer.parseInt( args[1] );
      }
      catch ( UnknownHostException e )
      {
          System.err.println("Invalid hostname");
          System.exit(1);     
      }
      catch ( Exception e ) 
      {
          System.err.println("Invalid port number");
          System.exit(1);
      }
      Client app = new Client();

      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
      app.runClient(host,port);
//      System.exit(0);
   }
}
