package com.Series40Book;

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


public class BTDeviceList extends List implements CommandListener{

  private BTDiscovery midlet;
  private BTUtil btutil;

  private Command back;
  private Command services;
  private Command deviceinfo;

  public BTDeviceList(BTDiscovery midlet, BTUtil btutil) {

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

    back = new Command ("Back", Command.BACK,1);
    services = new Command ("Services", Command.SCREEN, 2);
    deviceinfo = new Command ("DeviceInfo", Command.SCREEN, 3);

    addCommand (back);
    addCommand (services);
    addCommand (deviceinfo);

    setCommandListener( this );
  }

  public void commandAction(Command c, Displayable d) {
    if (c == back) {
      midlet.display.setCurrent(midlet.infoForm);
    }
    else if (c == services) {
      // we got to delete all existing records first
      midlet.services.removeAllElements();
      RemoteDevice remoteDevice = (RemoteDevice) midlet.devices.elementAt(getSelectedIndex());

      // clear the whole list
      int len = this.size();
      for ( int i=0; i < len; i++)
        { delete(0); }

      append("Please wait ...", null);
      midlet.BTDiscoverService(remoteDevice);
    }
    else if (c== deviceinfo) {

      RemoteDevice remoteDevice = (RemoteDevice) midlet.devices.elementAt(getSelectedIndex());
      DeviceClass deviceClass = (DeviceClass) midlet.deviceClasses.elementAt(getSelectedIndex());
      btutil.BTDisplayRemoteDevice (remoteDevice, deviceClass);

      midlet.infoForm.removeCommand(midlet.help);
      midlet.infoForm.addCommand(midlet.backtodevicelist);
      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 displaylist()
  {
    // clear the whole list
    int len = this.size();
    for ( int i=0; i < len; i++)
      { delete(0); }

    // for each devices on the list, show the friend name
    if ( this.midlet.devices.size() > 0 )
    {
      for (int i = 0; i < this.midlet.devices.size(); i++) {
        try {
          RemoteDevice device = (RemoteDevice) this.midlet.devices.elementAt(i);
          String fname = device.getFriendlyName(false);  // get it from device entry, not the device
          append(fname, null);
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }

}
