package sivantoledo.nxt;

public class Message {
  public final byte    mailbox;
  public final boolean important; // don't drop even if old; an extension of the NXT protocol
  public final byte[]  payload;
  
  public Message(byte mailbox, String m, boolean important) {
    this.mailbox = mailbox;
    this.important = important;

    if (m.length() > 59) m = "MSG TOO LONG";

    payload = new byte[ 3 + m.length() + 1 ];
    payload[0] = (byte) (m.length() + 1);
    for (int i=0; i<m.length(); i++)
      payload[1+i] = (byte) m.charAt(i);
    payload[ 1 + m.length() ] = 0; // string terminator    
  }
  
  public Message(byte mailbox, int m, boolean important) {
    this.mailbox = mailbox;
    this.important = important;

    payload = new byte[ 6 ];
    payload[0] = (byte) 5; // a four-byte int and a null terminator

    payload[1] = (byte) ((m      ) & 0xff); // LSB
    payload[2] = (byte) ((m >>  8) & 0xff); 
    payload[3] = (byte) ((m >> 16) & 0xff); 
    payload[4] = (byte) ((m >> 24) & 0xff); // MSB

    payload[5] = (byte) 0; // null terminator
 }

  public Message(byte mailbox, boolean m, boolean important) {
    this.mailbox = mailbox;
    this.important = important;

    payload = new byte[ 3 ];
    payload[0] = (byte) 2; // one byte and a null terminator

    payload[1] = m ? (byte) 1 : (byte) 0;

    payload[2] = (byte) 0; // null terminator
 }

  /*
   * The parsing methods require an offset, which should point to
   * the length field of the message (past the mailbox number).
   */

  
  public static int parseIntMessage(byte[] buffer, int offset) {
    //buffer[0] = (byte) 0x80;
    //buffer[1] = (byte) 0x09;
    //buffer[2] = (byte) mailbox;
    //buffer[3] = (byte) 5; // a four-byte int and a null terminator
    
    int x = 0;
    int t;
    
    t = 0; t = (int) buffer[offset+1] & 0xff; // LSB
    x |= t;
    t = 0; t = (int) buffer[offset+2] & 0xff;
    x |= t << 8; 
    t = 0; t = (int) buffer[offset+3] & 0xff;
    x |= t << 16; 
    t = 0; t = (int) buffer[offset+4] & 0xff;
    x |= t << 24; 
    return x;
  }
  
  public static boolean parseBooleanMessage(byte[] buffer, int offset) {
    //buffer[0] = (byte) 0x80;
    //buffer[1] = (byte) 0x09;
    //buffer[2] = (byte) mailbox;
    //buffer[3] = (byte) 2; // a byte and a null terminator
    
    return ( buffer[offset+1] != 0 );
  }

  public static String parseStringMessage(byte[] buffer, int offset) {
    //buffer[0] = (byte) 0x80;
    //buffer[1] = (byte) 0x09;
    //buffer[2] = (byte) mailbox;
    int length = buffer[offset];
    
    try {
      return new String(buffer,
                        offset+1, // offset
                        length-1,
                        "ASCII");
    } catch (java.io.UnsupportedEncodingException e) {
      // ASCII is always supported in Java
      return null;
    }
  }
}
