import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

/**
creates an applet with a grid and necessary buttons, labels etc. It also can add
figures that move around the grid.
@author Michael Donat
*/
public class Prog5 extends Applet implements ActionListener
{
   private Button connect;
   private List users;
   private TextField status;
   private TextArea chat;
   private TextField username;
   private TextField password;
   private TextField input;

   final String CONNECT_TEXT = "Connect!";
   private String server;
   private int port;
   private boolean connected = false;
   MsgSocket s;
   private final byte [] REPLY_Username = { 'U','s','e','r','n','a','m','e' };
   private final byte [] REPLY_Password = { 'P','a','s','s','w','o','r','d' };
   private final byte [] REPLY_NewPassword = { 'N','e','w','P','a','s','s','w','o','r','d' };
   private final byte [] REPLY_NewUser = { 'N','e','w','U','s','e','r' };
   private final byte [] REPLY_MainMenu = { 'M','a','i','n','M','e','n','u' };
   private final byte [] REPLY_Chat = { 'C','h','a','t' };

   /**
   Sets up the applet window
   */
   public void init()
   {
      server = getParameter( "server");
      port = new Integer( getParameter( "port")).intValue();
      connect = new Button( CONNECT_TEXT );
      users = new List(10,true);
      status = new TextField(15);
      chat = new TextArea(20,80);
      input = new TextField(80);
      username = new TextField(10);
      password = new TextField(10);
      status.setEditable( false );
      chat.setEditable( false );
      password.setEchoChar('*');
      add( chat );
      add( input );
      add( connect );
      add( users );
      add( username );
      add( password );
      add( status );
      s.addActionListener(this)
      input.addActionListener(this);
      connect.addActionListener(this);
   }

   public void destroy()
   {
      if( connected )
      {
         try
         {
            s.close();
         }
         catch( IOException excep )
         {
            status.setText( "IOException" );
         }
      }

   }
   /**
   If ActionEvent e is addFig and the movement text is not empty then
   add the selected figure( according to which radio button is selected ) to the
   list of gridfigures and draw the figure on the grid
   @param e is the Action that was done
   */
   private boolean match( byte [] one, byte [] two )
   {
      if( one.length != two.length )
         return false;
      int index = 0;
      while(  index < one.length && one[index] == two[index])
         index++;
      if( index < one.length )
         return false;
      return true;
   }
   public void actionPerformed( ActionEvent e )
   {
      if( e.getSource() == connect )
      {
         if( connected )
         {
            try
            {
               s.close();
               connected = false;
            }
            catch( IOException excep )
            {
               status.setText( "IOException" );
            }
         }
         makeConnection();
/*      while( true )
      {
         try
         {
            if( connected && s.hasData() )
            {
               Message msg = s.read();
               if( msg.getType() == Message.Text )
               {
                  chat.appendText( msg.toString() );
                  chat.appendText( "\n" );
               }
               if( msg.getType() == Message.Server )
               {
                  if( msg.toString().equals("UserList") )
                     users.clear();
                  else
                     users.add( msg.toString() );
               }
            }
         }
         catch( IOException excep )
         {
            status.setText( "IOException" );
         }
      }
*/
      }
      else if( e.getSource() == input && connected && input.getText().length() > 0 )
      {
         try
         {
            s.write( new Message( Message.Text, input.getText() ) );
         }
         catch( IOException excep )
         {
            status.setText( "IOException" );
         }
         status.setText( e.toString() );
         input.setText( "" );
      }
   }

   /**
   Sets the constants for location and then sets the location of the components
   also this sets the size of the applet window according to how
   big the grid is.
   */
   private void makeConnection()
   {
      try
      {
         s = new MsgSocket( server, port );
         Message reply = s.read();
         if( match( reply.getBytes(), REPLY_Username) )
            status.setText( reply.toString() );
         s.write( new Message( Message.Server, username.getText() ) );
         reply = s.read();
         status.setText( reply.toString() );
         if( match( reply.getBytes(), REPLY_Password ) )
         {
            s.write( new Message( Message.Server, password.getText() ) );
            reply = s.read();
            status.setText( reply.toString() );
            if( match( reply.getBytes(), REPLY_MainMenu ) )
               s.write( new Message( Message.Server, "Chat" ) );
            connected = true;
            reply = s.read();
            status.setText( reply.toString() );

         }
         else if( match( reply.getBytes(), REPLY_NewUser ) )
         {
            s.write( new Message( Message.Server, "YES" ) );
            reply = s.read();
            status.setText( reply.toString() );
            if( match( reply.getBytes(), REPLY_NewPassword ) )
            {
               s.write( new Message( Message.Server, password.getText() ) );
               reply = s.read();
               status.setText( reply.toString() );
               if( match( reply.getBytes(), REPLY_MainMenu ) )
                  s.write( new Message( Message.Server, "CHAT" ) );
            }
            connected = true;
            reply = s.read();
            status.setText( reply.toString() );
         }
         else
            s.close();
         if( connected )
            status.setText( "Connected" );
         else
            status.setText( "Error Connecting" );
      }
      catch( IOException excep )
      {
         status.setText( "IOException" );
      }
   }
   public void setPositions()
   {
      final int SPACING = 10;
//      users.setLocation( new Point( getWidth() - users.getWidth(), 0 ) );
//      connect.setLocation( new Point( users.getX(), users.getY() + users.getHeight() + SPACING ) );
   }

   /**
   puts the components on the applet
   @param g is the graphics used
   */
   public void paint ( Graphics g )
   {
      setPositions();
   }
}


