/*****************************************************************************
 *                                                                           *
 *         Licensed Materials - Property of IBM                              *
 *                                                                           *
 *         "Restricted Materials of IBM"                                     *
 *                                                                           *
 *         5799-QRY                                                          *
 *                                                                           *
 *         (C) Copyright IBM Corp. 1998                                      *
 *                                                                           *
 *****************************************************************************/
package com.ibm.devtools.SIPNoTE;

import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.java.swing.*;
import com.sun.java.swing.text.*;

/**
 * This class contains the GUI interface for sending a new Jephyr Message.
 * This class utilizes Swing version 1.0 for the GUI components.
 * <p>
 * The window is composed of three main areas: the To: field, the From:
 * field, and the message body.
 *
 * @author Bill Nagy
 *
 * @see JephyrWnd
 * @see SNWatch
 */
public class JSendWnd
{
  JFrame mainframe;
  JLabel tolabel, fromlabel;
  JTextField tofield;
  JNonEditableTextField fromfield;
  JPanel topanel, frompanel, headerpanel;
  JTextArea msgarea;
  PlainDocument msgdoc;
  Box headerbox;
  JPanel msgpanel;
  JScrollPane msgscroll;
  private JSendWndMouseListener wndmlistener;
  private JSendWndKeyListener wndklistener, mwndklistener;
  
  
  /**
   * Creates a new window with the To: field filled in.  Focus
   * will be set to the message body, but the user can still change
   * the list of recipients.
   *
   * @param tolist The list of recipients, separated by spaces or commas.
   */
  public JSendWnd(String tolist)
  {
    mainframe = new JFrame("Jephyr Send");
    wndmlistener = new JSendWndMouseListener(mainframe.getGlassPane(), this);
    mainframe.getGlassPane().setVisible(true);
    mainframe.getContentPane().setLayout(new BoxLayout(mainframe.getContentPane(), BoxLayout.Y_AXIS));
    
    headerpanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
    headerbox = Box.createVerticalBox();
    
    topanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
    tolabel = new JLabel("To:");
    tofield = new JTextField(tolist, 40);
    tofield.setBackground(Color.lightGray);
    wndklistener = new JSendWndKeyListener(tofield, this);
    topanel.add(tolabel);
    topanel.add(tofield);
    headerbox.add(topanel);

    frompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
    fromlabel = new JLabel("From:");
    fromfield = new JNonEditableTextField(System.getProperty("user.name"), 40);
    fromfield.setBorder(null);
    fromfield.setBackground(Color.lightGray);
    fromfield.setEditable(false);
    frompanel.add(fromlabel);
    frompanel.add(fromfield);
    headerbox.add(frompanel);

    headerpanel.add(headerbox);
    mainframe.getContentPane().add(headerpanel);

    msgdoc = new PlainDocument();
    msgarea = new JTextArea(msgdoc, null, 25, 75);
    mwndklistener = new JSendWndKeyListener(msgarea, this);
    
    msgscroll = new JScrollPane(msgarea);

    msgpanel = new JPanel();
    msgpanel.add(msgscroll);
    
    mainframe.getContentPane().add(msgpanel);
    mainframe.pack();
    mainframe.show();
    
    if (tolist != null)
      msgarea.requestFocus();
  }
  
  /**
   * Create a new window, with nothing in the To: field.  Focus will
   * be set to the To: field.
   */
  public JSendWnd()
  {
    this((String)null);
  }
  
  public static void main(String[] argv)
  {
    JSendWnd window = new JSendWnd();
  }
  
  /**
   * Create a new Jephyr message from the contents of this window,
   * and send it to the local SNClient.
   */
  public void sendMsg()
  {
    String[] tolist = new String[5];
    String[] msglines;
    String toline, token;
    int cnt = 0;
    
    /*Extract to*/
    toline = tofield.getText();
    StringTokenizer st = new StringTokenizer(toline);
    
    while (true)
      {
	try
	  {
	    token = st.nextToken(" ,");
	    if (cnt == tolist.length)
	      {
		String[] TempVar = new String[tolist.length+5];
		System.arraycopy(tolist, 0, TempVar, 0, cnt);
		tolist = TempVar;
	      }
	    tolist[cnt++] = token;
	  }
	catch (NoSuchElementException e)
	  {
	    if (tolist.length > cnt)
	      {
		String[] TempVar = new String[cnt];
		System.arraycopy(tolist, 0, TempVar, 0, cnt);
		tolist = TempVar;
	      }
	    break;
	  }
      }

    msglines = new String[msgarea.getLineCount()];

    for (cnt = 0; cnt < msglines.length; cnt++)
      {
	try
	  {
	    msglines[cnt] =
	      (msgdoc.getText(msgarea.getLineStartOffset(cnt),
			      msgarea.getLineEndOffset(cnt)-msgarea.getLineStartOffset(cnt)));
	  }
	catch (BadLocationException e)
	  {
	  }
      }

    Properties props = new Properties();
    FileInputStream fin;
    int localport;

    try
      {
	fin = new FileInputStream(".jephyr");
	props.load(fin);
      }
    catch (FileNotFoundException e)
      {
      }
    catch (IOException e)
      {
	System.err.println("I/O Error loading .jephyr file --> "+e);
	return;
      }

    localport = (new Integer(props.getProperty("JClient.jport",
					       "5062")).intValue());
    JMessage message = new JMessage(msglines,
				    System.getProperty("user.name"),
				    tolist);
    try
      {
	Socket server = new Socket("127.0.0.1", localport);
	ObjectOutputStream out =
	  new ObjectOutputStream(server.getOutputStream());
	ObjectInputStream in =
	  new ObjectInputStream(server.getInputStream());
	
	out.writeObject(message);
	out.flush();
	
	server.close();
      }
    catch(IOException e)
      {
	System.err.println("I/O Error --> " + e);
      }
  }
}


/* The classes below are responsible for processing events
   which this window may receive.*/
class JSendWndKeyListener extends KeyAdapter
{
  private Component attachpoint;
  private JSendWnd sendwnd;

  JSendWndKeyListener(Component attachpoint, JSendWnd sendwnd)
  {
    this.attachpoint = attachpoint;
    this.sendwnd = sendwnd;

    attachpoint.addKeyListener(this);
  }

  public void keyPressed(KeyEvent e)
  {
    
    /*If we get a ctrl-s, send the message*/
    if ((e.getKeyCode() == KeyEvent.VK_S) && e.isControlDown())
      {
	sendwnd.sendMsg();
	sendwnd.mainframe.dispose();
      }

    /*If we get a ctrl-c, kill this window*/
    if ((e.getKeyCode() == KeyEvent.VK_C) && e.isControlDown())
      sendwnd.mainframe.dispose();

  }

}

class JSendWndMouseListener extends MouseAdapter
{
  private Component glasspane;
  private JSendWnd sendwnd;

  JSendWndMouseListener(Component glasspane, JSendWnd sendwnd)
  {
    this.glasspane = glasspane;
    this.sendwnd = sendwnd;
    glasspane.addMouseListener(this);
  }

  public void mouseClicked(MouseEvent e)
  {
    boolean b1 = (e.getModifiers() & e.BUTTON3_MASK) > 0;

    if (b1)
      {
	sendwnd.sendMsg();
	sendwnd.mainframe.dispose();
      }
  }
}

class JNonEditableTextField extends JTextField
{
  JNonEditableTextField(String text, int columns)
  {
    super(text, columns);
  }

  public boolean isFocusTraversable()
  {
    return false;
  }
}
