package profiles;

import java.util.Vector;

public class TextMessage implements Message{
  String msg;
  String src;
  Vector route;
  int type;
  int ttl = 0;

  public TextMessage(String msg, String src, int type) {
    this.msg = msg;
    this.src = src;
    this.type = type;
  }

  public TextMessage(String msg, String src, int type, int ttl) {
    this.msg = msg;
    this.src = src;
    this.type = type;
    this.ttl = ttl;
  }


  public Vector getRoute() {
    return route;
  }

  public void setRoute(Vector l) {
    route = l;
  }

  public String getSrcDevice() {
    return src;
  }

  public Object getMessage() {
    return msg;
  }

  public int getType() {
    return type;
  }

  public String toString() {
    StringBuffer sbuff = new StringBuffer();
    sbuff.append(getType());
    sbuff.append(src);
    for (int i = 0; i < route.size(); i++) {
      sbuff.append(',');
      sbuff.append((String)route.elementAt(i));
    }

    sbuff.append('$');
    sbuff.append(ttl);
    sbuff.append('@');
    sbuff.append(msg);

    return sbuff.toString();
  }

  public static TextMessage fromString(String str) {
    Vector route = new Vector();

    int type = Integer.parseInt(""+str.charAt(0));

    int pos = 1;

    // Lettura src
    StringBuffer srcBuffer = new StringBuffer();
    do {
      srcBuffer.append(str.charAt(pos));
      pos++;
    } while (str.charAt(pos) != ',' && str.charAt(pos) != '@' && str.charAt(pos) != '$');


    // Lettura route
    while (str.charAt(pos) != '$') {
      pos++;
      StringBuffer intBuf = new StringBuffer();
      do {
        intBuf.append(str.charAt(pos));
        pos++;
      } while (str.charAt(pos) != ',' && str.charAt(pos) != '@');
      route.addElement(intBuf.toString());
    }
    pos++;

    // Lettura ttl
    StringBuffer intBuf = new StringBuffer();
    while (str.charAt(pos) != '@') {
      intBuf.append(str.charAt(pos));
      pos++;
    }
    pos++;

    int ttl = Integer.parseInt(intBuf.toString());

    String src = srcBuffer.toString();
    String msg = str.substring(pos);
    TextMessage theMessage = new TextMessage(msg,src,type,ttl);
    theMessage.route = route;
    return theMessage;
  }

  public int getTimeToLive() {
    return ttl;
  }

  public int decTimeToLive() {
    return --ttl;
  }
}
