// Generated by CoffeeScript 1.7.1
var MYSTERY_HEADER_LENGTH, RETRIES, SQL_SERVER_BROWSER_PORT, TIMEOUT, dgram, parseBrowserResponse;

dgram = require('dgram');

SQL_SERVER_BROWSER_PORT = 1434;

TIMEOUT = 2 * 1000;

RETRIES = 3;

MYSTERY_HEADER_LENGTH = 3;

exports.instanceLookup = function(server, instanceName, callback, timeout, retries) {
  var error, makeAttempt, message, retriesLeft, socket, timedOut, timer;
  timeout = timeout || TIMEOUT;
  retriesLeft = retries || RETRIES;
  timer = void 0;
  socket = void 0;
  message = function(message, rinfo) {
    var port;
    if (timer) {
      clearTimeout(timer);
      timer = void 0;
    }
    message = message.toString('ascii', MYSTERY_HEADER_LENGTH);
    port = parseBrowserResponse(message, instanceName);
    socket.close();
    if (port) {
      return callback(void 0, port);
    } else {
      return callback("Port for " + instanceName + " not found in " + message);
    }
  };
  error = function(err) {
    if (timer) {
      clearTimeout(timer);
      timer = void 0;
    }
    socket.close();
    return callback("Failed to lookup instance on " + server + " - " + err.message);
  };
  timedOut = function() {
    timer = void 0;
    socket.close();
    return makeAttempt();
  };
  makeAttempt = function() {
    var request;
    if (retriesLeft > 0) {
      retriesLeft--;
      request = new Buffer([0x02]);
      socket = dgram.createSocket('udp4');
      socket.on('error', error);
      socket.on('message', message);
      socket.send(request, 0, request.length, SQL_SERVER_BROWSER_PORT, server);
      return timer = setTimeout(timedOut, timeout);
    } else {
      return callback("Failed to get response from SQL Server Browser on " + server);
    }
  };
  return makeAttempt();
};

parseBrowserResponse = function(response, instanceName) {
  var getPort, instance, instances, name, p, parts, port, value, _i, _j, _len, _ref;
  instances = response.split(';;');
  for (_i = 0, _len = instances.length; _i < _len; _i++) {
    instance = instances[_i];
    parts = instance.split(';');
    for (p = _j = 0, _ref = parts.length - 1; _j <= _ref; p = _j += 2) {
      name = parts[p];
      value = parts[p + 1];
      if (name === 'tcp' && getPort) {
        port = parseInt(value, 10);
        return port;
      }
      if (name === 'InstanceName') {
        if (value.toUpperCase() === instanceName.toUpperCase()) {
          getPort = true;
        } else {
          getPort = false;
        }
      }
    }
  }
  return void 0;
};

exports.parseBrowserResponse = parseBrowserResponse;
