/* Chat applet written 15-17 December 1998
 * by xanni@glasswings.com.au (Andrew Pam)
 * Copyright (c) 1998 Glass Wings
 *
 * Compatible with Java 1.0 for old browsers
 */

import java.awt.*;
import java.util.*;

class ChatCanvas extends Canvas
{
  Color bgColor;
  Font font;
  FontMetrics fontMetrics;
  int fontHeight;
  int startLine;
  String[] lineArray;
  String[] userArray;
  Color[] colorArray;

  protected Color toColor(String value, Color def)
  {
    if (value != null)
    {
      try
      {
        if (value.startsWith("#")) value = value.substring(1);
        def = new Color(Integer.parseInt(value, 16));
      }
      catch (Exception e)
      { }
    }
    return def;
  }

  /** setUsers() initialises userArray and colorArray
   *  from two comma-separated strings
   */
  public void setUsers(String names, String colors)
  {
    int l;
    StringTokenizer sn, sc;

    if (names == null) names = "";
    if (colors == null) colors = "";
    sn = new StringTokenizer(names, ",");
    sc = new StringTokenizer(colors, ",");
    l = sn.countTokens() + 1;
    userArray = new String[l];
    userArray[0] = "";
    colorArray = new Color[l];
    colorArray[0] = Color.black;
    for (int i = 1; i < l; i++)
    {
      userArray[i] = sn.nextToken();
      if (sc.hasMoreTokens())
        colorArray[i] = toColor(sc.nextToken(), Color.black);
      else
        colorArray[i] = Color.black;
    }
  }

  /** getUser() returns the index of a user within userArray */
  public int getUser(String name)
  {
    int u;

    // Linear search is fine for small numbers
    for (u = 1; u < userArray.length; u++)
    { if (name.equalsIgnoreCase(userArray[u])) break; }
    if (u >= userArray.length) u = 0;	// Not found
    return u;
  }

  public synchronized void setFont(Font f)
  {
    super.setFont(font = f);
    fontMetrics = getFontMetrics(font);
    fontHeight = fontMetrics.getMaxAscent() + fontMetrics.getMaxDescent() +
                 fontMetrics.getLeading();
  }

  public void paint(Graphics g)
  {
    // In case we get called before anything has been initialised
    if (lineArray == null) return;

    int y = fontMetrics.getMaxAscent();

    int endLine = startLine + (size().height / fontHeight);
    if (endLine > lineArray.length) endLine = lineArray.length;
    for (int i = startLine; i < endLine; i++)
    {
      String l = lineArray[i];
      // NOTE: This will only work if there are less than 10 users.
      //       To handle more, find n = the number of digits at the start
      //       of l and change to u = Integer.parseInt(l.substring(0, n))
      int u = (int) (l.charAt(0) - '0');
      g.setColor(colorArray[u]);
      if (u == 0)
        g.drawString(l.substring(1), 0, y);
      else
        g.drawString(userArray[u] + ": " + l.substring(1), 0, y);
      y += fontHeight;
    }
  }
}

public class Chat extends java.applet.Applet
{
  static final int HMARGIN = 20;

  ChatCanvas canvas = new ChatCanvas();
  Scrollbar sb;

  public String getAppletInfo()
  {
    return "Chat applet by Andrew Pam, Copyright (c) 1998 Glass Wings";
  }

  public String[][] getParameterInfo()
  {
    String[][] paramInfo =
    {
      {"bgcolor",	"Hexadecimal color value",	"Background color"},
      {"font",		"Font name (optional size)",	"Chat text font"},
      {"title",		"String",			"Title bar text"},
      {"title.bgcolor",	"Hexadecimal color value",	"Title bar color"},
      {"title.color",	"Hexadecimal color value",	"Title text color"},
      {"title.font",	"Font name (optional size)",	"Title font"},
      {"user.names",	"Comma-separated text",		"User names"},
      {"user.colors",	"Comma-separated hex color values",	"User colors"},
      {"line[1-n]",	"User name, colon, text string",	"Chat text"}
    };
    return paramInfo;
  }

  protected Color getColorParameter(String param, Color def)
  {
    return canvas.toColor(getParameter(param), def);
  }

  protected Font getFontParameter(String param,
                                  String name, int style, int size)
  {
    if ((param = getParameter(param)) != null)
    {
      StringTokenizer st = new StringTokenizer(param);
      name = st.nextToken();
      // NOTE: We could check for "Bold" and/or "Italic" here too
      if (st.hasMoreTokens())
      {
        try
        { size = Integer.parseInt(st.nextToken()); }
        catch (Exception e)
        { }
      }
    }
    return new Font(name, style, size);
  }

  protected void parseText()
  {
    int width = size().width - HMARGIN;	// Horizontal margin
    Vector v = new Vector(10, 10);	// Guess at ten lines of dialogue
    int i = 1;
    String s = getParameter("line" + i);
    while (s != null)
    {
      int nw = 0;
      int u = 0;
      int p = s.indexOf(':');
      if (p > -1)
      {
        String name = s.substring(0, p);
        u = canvas.getUser(name);
        if (u > 0)
        {
          nw = canvas.fontMetrics.stringWidth(name + ": ");
          s = s.substring(p + 2);
        }
      }
      StringTokenizer st = new StringTokenizer(s);
      s = null;
      while (st.hasMoreTokens())
      {
        String n = st.nextToken();
        String t = (s == null) ? n : (s + " " + n);
        if ((nw + canvas.fontMetrics.stringWidth(t)) < width)
        { s = t; }
        else
        { v.addElement(u + s); s = n; }
      }
      v.addElement(u + s);
      
      s = getParameter("line" + (++i));
    }
    canvas.lineArray = new String[v.size()];
    v.copyInto(canvas.lineArray);
  }

  public void init()
  {
    String s;
    Label title;

    setBackground(canvas.bgColor = getColorParameter("bgcolor", Color.white));
    setLayout(new BorderLayout());
    if ((s = getParameter("title")) != null)
    {
      title = new Label(s, Label.CENTER);
      title.setFont(getFontParameter("title.font", "Helvetica", Font.BOLD, 18));
      title.setBackground(getColorParameter("title.bgcolor", Color.gray));
      title.setForeground(getColorParameter("title.color", Color.black));
      add("North", title);
    }
    add("East", sb = new Scrollbar(Scrollbar.VERTICAL));
    add(canvas);
    canvas.setFont(getFontParameter("font", "Courier", Font.PLAIN, 14));
    canvas.setUsers(getParameter("user.names"), getParameter("user.colors"));
    parseText();
  }

  public void start()
  {
    // Set up the scrollbar
    sb.setValues(0, canvas.size().height / canvas.fontHeight,
                 0, canvas.lineArray.length);
  }

  public boolean handleEvent(Event e)
  {
    switch (e.id)
    {
      case Event.SCROLL_LINE_UP:
      case Event.SCROLL_LINE_DOWN:
      case Event.SCROLL_PAGE_UP:
      case Event.SCROLL_PAGE_DOWN:
      case Event.SCROLL_ABSOLUTE:
        canvas.startLine = ((Integer) e.arg).intValue();
        canvas.repaint();
    }
    return super.handleEvent(e);
  }
}
