package profilesj2me;

import profiles.*;
import javax.bluetooth.*;

class J2MEDevice implements Device {
  String id = null;
  String url = null;
  RoutingTable routingTable=null;

  protected J2MEDevice() {
  }

  J2MEDevice(String id) {
    this.id = id;
  }

  public String getURL() {
    return url;
  }

  public void setURL(String url) {
    this.url = url;
  }


  public String getId() {
    return id;
  }

  public RoutingTable getRoutingTable() {
    return routingTable;
  }

  public void refresh(BasicService basicService) {

  }

  // Mostra un dialogo informativo quando è ricevuto un messaggio
  public void receive(Message message) {
    System.out.println("J2MEDevice receive: " + message);
    if (message.getMessage().equals("PREQ")) {
      ProfilesJ2ME.getInstance().getProfileMatcher().
          profileRequested(message.getSrcDevice());
    } else {
      if (((String)message.getMessage()).charAt(0) == '@') {
        ProfilesJ2ME.getInstance().getProfileMatcher()
            .addProfile(Profile.fromString((String)message.getMessage()));
      } else {
        // Notifica il match sullo schermo
        javax.microedition.lcdui.Alert alert =
            new javax.microedition.lcdui.Alert("Match!");
        alert.setString((String)message.getMessage());
        alert.setType(javax.microedition.lcdui.AlertType.INFO);
        alert.setTimeout(2000);
        javax.microedition.lcdui.Display.getDisplay(profilesj2me.ProfilesJ2ME.getInstance())
            .setCurrent(alert);
      }
    }
  }

  public String toString() {
    return "{"+ getId() +
        (getRoutingTable() == null? "[]" : getRoutingTable().toString()) + "}";
  }

  public static J2MEDevice fromString(String str) {
    J2MEDevice dev = new J2MEDevice();
    parseJ2MEDevice(str, dev);
    return dev;
  }

  static int parseJ2MEDevice(String str, J2MEDevice dev) {
    int pos = 0;
    if (str.charAt(pos) != '{')
      throw new IllegalArgumentException("Missing {");

    StringBuffer sbuff = new StringBuffer();

    pos = 1;
    while (str.charAt(pos) != '[') {
      sbuff.append(str.charAt(pos));
      pos++;
    }


    RoutingTable rt = new RoutingTable(dev);
    pos += parseRoutingTable(str.substring(pos), rt);
    if (str.charAt(pos) != '}')
      throw new IllegalArgumentException("Missing }");

    dev.url = "";
    dev.id = sbuff.toString();
    dev.routingTable = rt;
    return pos++;
  }

  static int parseRoutingTable(String str, RoutingTable rt) {
    int pos = 0;
    if (str.charAt(pos) != '[')
      throw new IllegalArgumentException("Missing [");

    pos++;
    while (str.charAt(pos) != ']') {
      if (str.charAt(pos) == '{') {
        J2MEDevice d = new J2MEDevice();
        pos += parseJ2MEDevice(str.substring(pos), d);
        rt.addDevice(d);
      }
      pos++;
    }

    return++pos;
  }

  void setRoutingTable(RoutingTable rt) {
    routingTable = rt;
  }
}