package test;

import com.wilko.jaim.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Enumeration;

/**
 * Example test code for Jaimlib. Login to AIM, look up your buddies,
 * and disconnect.
 *
 * Run this program with:
 *  java test.JaimMessageTest yourname yourpass
 * It'll login with yourname and yourpass, pause for a while as the
 * configuration information is asynchronously uploaded, and then list
 * all your buddies.
 */

public class JaimBuddiesTest implements JaimEventListener {

  // Hostname and port number to connect to.
  //
  private static String HOST = "toc.oscar.aol.com";
  private static int PORT = 9898;

  // Our connection to the AIM server.
  //
  private JaimConnection connection;


  public JaimBuddiesTest(String name, String pass) {
    try {
      connection = new JaimConnection(HOST, PORT);
      connection.connect();
      connection.watchBuddy(name);
      connection.logIn(name, pass, 15000);
      connection.addEventListener(this);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(1);
    }
  }

  public void listBuddies() {
    try {
      // Wait a few seconds to make sure the data has come through.
      // The *correct* behaviour would actually be to await a
      // ConfigTocResponse, which is the event that indicates that a
      // configuration has been received.
      //
      System.out.println("Waiting...");
      Thread.sleep(10000);

      if (connection.isConfigValid() == false) {
        System.out.println("No config information received before timeout.");
      } else {
        Collection groups = connection.getGroups();
        Iterator i = groups.iterator();
        while (i.hasNext()) {
          Group group = (Group) i.next();
          int count = group.getBuddyCount();
          System.out.println(count + " buddies in group " + group.getName() + ":");
	  Enumeration e = group.enumerateBuddies();
          while (e.hasMoreElements()) {
            Buddy buddy = (Buddy) e.nextElement();
            System.out.println(buddy.getName());
          }
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  public void close() {
    connection.logOut();
  }


  // This method is requied by the JaimEventListener interface. It
  // processes notification events from the JaimConnection object.
  // We don't do anything here except note that they arrived. (The useful
  // information, though, is in the TocResponse.)
  // 
  public void receiveEvent(JaimEvent ev) {
    System.out.println("Received " + ev.getTocResponse().getClass());
  }


  public static void main(String args[]) {
    if (args.length != 2) {
      System.err.println("Usage: java test.JaimBuddiesTest yourname yourpassword");
      System.exit(1);
    }
    JaimBuddiesTest test = new JaimBuddiesTest(args[0], args[1]);
    test.listBuddies();
    test.close();
  }

}
