import javax.swing.*;
import java.net.*;
import java.io.*;

public class ChatConnection implements Runnable
{
   private Socket ConnectionToServer;
   private BufferedReader CCInStream;
   private PrintWriter CCOutStream;
   
   private JTextArea ChatWindow;
   private JScrollPane ChatWindowPane;
   
   /**
   * @author Michael Wales
   * Chat connection constructor.  The JTextArea is the text area to write incoming chat text
   * to.  The JScrollPane is needed to constantly reset the view to the bottom of the scroll pane
   * when the text starts to scroll off the bottom.
   */
   public ChatConnection(JTextArea X, JScrollPane Y)
   {
      ChatWindow = X;
      ChatWindowPane = Y;
   }
   
   /** 
   * Opens a connection to the server at the given IP address and port number.  This also starts
   * a thread that will listen to that connection and output incoming text to the chat window.
   */
   public boolean open(String IPAddress, int PortNumber)
   {
      System.out.println("Opening connection to:  " + IPAddress + ":" + PortNumber);
      
      // Open socket connection
      try
      {
         ConnectionToServer = new Socket(IPAddress, PortNumber);
      }
      catch (Exception E)
      {
         ChatWindow.append("CONNECTION FAILED!!!\n\n");
         return false;
      }
      
      // Setup both incoming and outgoing chat streams
      try
      {
         CCInStream = new BufferedReader( new InputStreamReader(ConnectionToServer.getInputStream()) );
         CCOutStream = new PrintWriter( ConnectionToServer.getOutputStream(), true );
      }
      catch (Exception E)
      {
         ChatWindow.append("MiniChat ERROR:  Couldn't connect input and output streams to chat server\n");
         return false;
      }
      
      // Start the listening thread
      Thread ListenThread = new Thread(this);
      ListenThread.start();
      
      // Connection was opened successfully
      ChatWindow.append("Connected!\n\n");
      return true;   
   }
   
   /**
   * Closes the chat connection input and output streams
   */
   public void close ()
   {
      try
      {
         CCOutStream.close();
         CCInStream.close();
         ConnectionToServer.close();
      }
      catch (Exception E)
      {
         ChatWindow.append("MiniChat ERROR:  Error closing connection to chat server");
      }
   }
   
   /**
   * This method is from the runnable interface.  This method listends for incoming text,
   * and displays any incoming text to the JTextArea.
   */
   public void run()
   {
      String MessageText = null;
      int SBMax;
      
      for(;;)
      {
         try
         {
            MessageText = CCInStream.readLine();
            if ( !MessageText.equals("null") )
            {
               ChatWindow.append(MessageText + "\n");
               SBMax = ChatWindowPane.getVerticalScrollBar().getMaximum();
               ChatWindowPane.getVerticalScrollBar().setValue(SBMax);
            }
         }
         catch (Exception E)
         {
            ChatWindow.append("MiniChat ERROR:  Bad incoming data\n");
            return;
         }        
      }
   }
   
   /**
   * Outputs a message to all the other chat users.
   */
   public void sendMessage(String Text)
   {
      CCOutStream.println(Text);
   }
   
}
