/**
 * A general purpose message container.
 *
 * @file     Message.js
 * @date     2008-10-24 00:20 HST
 * @author   Paul Reuter
 * @version  1.1
 */


/**
 * A splitable message handler extended by NMEA.
 *
 * @constructor
 * @param {string} message The message we're abstracting.
 * @return {object} A new Message object.
 */
function Message(message,delim) { 
  this.message = message || '';
  this.fields  = [];
  this.delim   = '\t';
  if( typeof(delim) != "undefined" ) { 
    this.delim = delim;
  }
  this.fields = this.message.split(this.delim);
  return this;
}; // END: constructor Message(message)


/**
 * Get the current message.
 *
 * @public
 * @return {string} The message.
 */
Message.prototype.getMessage = function() { 
  return this.message;
}; // END: function getMessage()


/**
 * Assigns a new value to the message. Consequently resets internal stuff.
 *
 * @public
 * @param {string} message A new message string.
 * @return {boolean} true always.
 */
Message.prototype.setMessage = function(message) { 
  this.message = message;
  return true;
}; // END: function setMessage(message)


/**
 * Splits the message and returns the field requested.
 *
 * @public
 * @param {int} field_no Field number to return, starting from zero.
 * @param {string} delim A delimiter to split the current message with.
 * @return {mixed} The {field_no} value or null if not found.
 */
Message.prototype.getField = function(field_no,delim) {
  if( !delim || this.delim == delim ) { 
    if( typeof(this.fields[field_no]) != "undefined" ) { 
      return this.fields[field_no];
    }  
    return null;
  }
  
  this.delim = delim;
  this.fields = this.message.split(delim);
  if( typeof(this.fields[field_no]) != "undefined" ) { 
    return this.fields[field_no];
  }
  return null;
}; // END: function getField(field_no,[delim]);  

/**
 * Splits the message and returns its fields.
 *
 * @public
 * @param {string} delim A delimiter to split the current message with.
 * @return {array} An array of field contents.
 */
Message.prototype.getFields = function(delim) { 
  if( !delim || this.delim == delim ) {
    return this.fields.slice();
  }
  this.delim = delim;
  this.fields = this.message.split(delim);
  return this.fields.slice();
}; // END: function getFields
