package com.Series40Book;

import javax.microedition.lcdui.*;
import javax.bluetooth.*;

import java.util.*;

public class BTServiceList extends List implements CommandListener{

  private BTDiscovery midlet;
  private BTUtil btutil;

  private Command back;


  public BTServiceList(BTDiscovery midlet, BTUtil btutil) {

    super("BTServiceList", List.IMPLICIT);
    this.midlet  = midlet;
    this.btutil = btutil;

    back = new Command ("Back", Command.BACK,1);

    addCommand (back);
    setCommandListener( this );
  }

  public void commandAction(Command c, Displayable d) {
    if (c == back) {
     midlet.display.setCurrent(midlet.infoForm);
    }

  }

  /**
   * clear the screen and display RemoteDevice friendly names on screen.
   * The deivces are retrieve from DiscoveryMain.devices vector.
   */
  public void displayservices()
  {
    // clear the whole list
    int len = this.size();
    for (int i = 0; i < len; i++) {
      delete(0);
    }

    for (int i = 0; i < this.midlet.services.size(); i++) {
      try {
        ServiceRecord rec = (ServiceRecord) this.midlet.services.elementAt(i);

        // get the 1ist element of ServiceClassIDList
        // and translate it to the human friendly name
        DataElement e = rec.getAttributeValue(0x0001); // ServiceClassIDList
        Enumeration enum = (Enumeration) e.getValue();
        DataElement e2 = (DataElement) enum.nextElement();
        Object v = e2.getValue();

        // name looks like "#1 SerialPort"
        String name = "#" + i + " " + btutil.BTUUIDToName( (UUID) v);
        append(name, null);  // append to List

      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }

  }

}
