'use strict';

var request = require("request");
var querystring = require("querystring");
var helpers = require("./helpers");

var API_BASE = "http://api-m2x.att.com/v1";
var USER_AGENT = "M2X/0.0.2 (node.js)";

var Client = function(apiKey, apiBase) {
    this.apiKey = apiKey;
    this.apiBase = apiBase || API_BASE;

    this.defaultHeaders = {
        "User-Agent": USER_AGENT,
        "X-M2X-KEY": this.apiKey
    };

    // Define request methods by verb
    ['get', 'post', 'put', 'del', 'head', 'options', 'patch'].
        forEach(function(verb) {
            this[verb] = function(path, options, cb) {
                this.request(verb, path, options, cb);
            };
        }.bind(this));
};

Client.prototype.request = function(verb, path, options, cb) {
    var body, headers;

    if (typeof options === "function") {
        // callback was sent in place of options
        cb = options;
        options = {};
    }

    headers = helpers.extend(this.defaultHeaders, options.headers || {});

    if (! headers["Content-Type"]) {
        headers["Content-Type"] = "application/x-www-form-urlencoded";
    }

    if (options.params) {
        switch (headers["Content-Type"]) {
        case "application/json":
            body = JSON.stringify(options.params);
            break;
        case "application/x-www-form-urlencoded":
            body = querystring.stringify(options.params);
            break;
        default:
            throw "Unrecognized Content-Type `" + headers["Content-Type"] + "`";
        }
    }

    request({
        url: this.apiBase + path,
        qs: options.qs,
        method: verb,
        headers: headers,
        body: body
    }, function(error, response, body) {
        var data = JSON.parse(body);
        // TODO: make sure there are no problems parsing JSON?
        cb.call(this, data, error, response);
    });
};

module.exports = Client;

@@ -1711,24 +1711,46 @@
 se, body) %7B%0A
+        if (cb) %7B%0A    
         var 
@@ -1755,16 +1755,23 @@
 r data =
+ body ?
  JSON.pa
@@ -1779,18 +1779,27 @@
 se(body)
-;%0A
+ : %7B%7D;%0A    
         
@@ -1861,16 +1861,20 @@
         
+ 
+   
 cb.call(
@@ -1903,16 +1903,26 @@
 ponse);%0A
+        %7D%0A
     %7D);%0A

Check whether we got a callback before using it.