var request = require('request');
var util = require('util');
var EJSON = require('mongodb-extended-json')
var Endpoint = require('./Endpoint')


/******************************************************************************
 * @class RestClient < Endpoint
 * @constructor
 *
 * @param url
 * @param options
 */
function RestClient(url, options) { // XXX what are the options?
  // call super
  Endpoint.call(this)

  this.url = url
  // setting this.client = this !!! this is so that child endpoint get this.client set properly
  // when calling end
  this.client = this
  this.defaultOptions = options || {}

  // setup authenticator
  if ("authentication" in this.defaultOptions) {
    this._setupAuthentication(this.defaultOptions["authentication"])
  }
}

// inherit Endpoint
util.inherits(RestClient, Endpoint)

RestClient.prototype._setupAuthentication = function(authentication){
  if( authentication.type === "api-key") {
    this._setupApiKeyAuthentication(authentication)
  }
}

RestClient.prototype._setupApiKeyAuthentication = function(authentication){
  var apiKeyParameterName = authentication.apiKeyParameterName || "API_KEY"
  var apiKeyLocation = authentication.apiKeyLocation || "header"

  if(apiKeyLocation === "header") {
    if( !this.defaultOptions.headers){
      this.defaultOptions.headers = {}
    }
    this.defaultOptions.headers[apiKeyParameterName] = authentication.apiKey
  }else if(apiKeyLocation === "query"){

  }
}



/****************************************************************************************************
 * exports
 */
module.exports = RestClient

@@ -812,16 +812,163 @@
 point)%0A%0A
+/******************************************************************************%0A * _setupAuthentication()%0A * @param authentication%0A * @private%0A */%0A
 RestClie
@@ -1023,24 +1023,25 @@
 hentication)
+ 
 %7B%0A  if( auth
@@ -1132,16 +1132,167 @@
 %0A  %7D%0A%7D%0A%0A
+/******************************************************************************%0A * _setupApiKeyAuthentication%0A * @param authentication%0A * @private%0A */%0A
 RestClie
@@ -1357,16 +1357,17 @@
 ication)
+ 
 %7B%0A  var 
@@ -1575,16 +1575,17 @@
 headers)
+ 
 %7B%0A      
@@ -1738,18 +1738,250 @@
 %22query%22)
+ 
 %7B%0A
+    if( !this.defaultOptions.query) %7B%0A      this.defaultOptions.query = %7B%7D%0A    %7D%0A    this.defaultOptions.query%5BapiKeyParameterName%5D = authentication.apiKey%0A  %7Delse%7B%0A    throw Error(%22Unknown apiKeyLocation '%22 + apiKeyLocation + %22'%22)
 %0A  %7D%0A%7D%0A%0A

support api key auth in query