'use strict';

var dgram = require('dgram'),
    util = require('util');

/*
 * Generates an xAP message block, given a messageType and object.
 */
var generateMessage = function (messageType, message) {
    var body = messageType + '\n{\n';
    Object.keys(message).forEach(function(key) {
      body += util.format('%s=%s\n', key, message[key]);
    });
    body += '}\n';
    return body;
};

var XAPBroadcaster = function (options) {
  var self = this;
  options = options || {};

  self.version = options.version || 12;
  self.class = options.class;
  self.source = options.source;
  self.target = options.target;
  self.uid = options.uid;
  self.broadcast = options.broadcast || '255.255.255.255';
  self.port = options.port || 3639;

  if (typeof self.class === 'undefined') {
    throw new Error('Must provide a class.');
  }
  if (typeof self.source === 'undefined') {
    throw new Error('Must provide a source.');
  }
  if (typeof self.uid === 'undefined') {
    throw new Error('Must provide a uid.');
  }
}

XAPBroadcaster.prototype.send = function (messageType, message, callback) {
  var self = this,
      client = dgram.createSocket('udp4'),
      header = {v: self.version, hop: 1, uid: self.uid, class: self.class, source: self.source},
      message = generateMessage(messageType, message);

  if (typeof self.target != 'undefined') {
    header.target = self.target;
  }
  header = generateMessage('xap-header', header);
  var buffer = new Buffer(header + message);

  client.bind(function() {
    client.setBroadcast(true);
    client.send(buffer, 0, buffer.length, self.port, self.broadcast, function(err, bytes) {
      client.close();
      if (typeof callback === 'function') {
        callback(err, bytes);
      }
    });
  });
}

exports.XAPBroadcaster = XAPBroadcaster;
exports.generateMessage = generateMessage;

@@ -518,16 +518,42 @@
  %7C%7C 12;%0A
+  self.uid = options.uid;%0A
   self.c
@@ -642,34 +642,8 @@
 et;%0A
-  self.uid = options.uid;%0A
   se
@@ -1251,64 +1251,111 @@
 rce%7D
-,%0A      message = generateMessage(
+;%0A%0A  if (typeof messageType === 'undefined') %7B%0A    throw new Error('Must provide a 
 message
-Type, message);
+ type.');%0A  %7D
 %0A%0A  
@@ -1482,16 +1482,71 @@
 eader);%0A
+  var message = generateMessage(messageType, message);%0A
   var bu

Check message type undefined