       grant_type    : "refresh_token"
     @_proxy "POST", "user/token", parameters, headers
 
-
   api: (agent, method, url, token, parameters) ->
     headers = {}
     headers["user-agent"] = agent if agent

###
"use strict"

request = require "request"
qs      = require "querystring"
Hope    = require "hope"

Appnima =

  host    : "http://api.appnima.com/"
  key     : ""

  open: (connection) ->
    promise = new Hope.Promise()
    if connection.key? then @key = connection.key
    if connection.host? then @host = connection.host
    console.log " ✓".green, "Appnima", "listening at".grey, "#{@host}".underline.blue
    promise.done null, true
    promise


  _proxy: (method, url, parameters = {}, headers = {}) ->
    promise = new Hope.Promise()

    options =
      host    : @host
      port    : @port
      path    : "/#{url}"
      method  : method.toUpperCase()
      headers : headers
      agent   : false

    if parameters? and (options.method is "GET" or options.method is "DELETE")
      options.path += "?#{qs.stringify(parameters)}"
    else
      body = qs.stringify parameters
      options.headers["Content-Type"] = "application/x-www-form-urlencoded"
      options.headers["Content-Length"] = body.length

    client = http.request options, (response) =>
      body = ""
      response.setEncoding "utf8"
      response.on "data", (chunk) -> body += chunk
      response.on "end", ->
        body = JSON.parse body if body?
        if response.statusCode >= 400
          error = code: response.statusCode, message: body.message
          body = undefined
        promise.done error, body

    client.on "error", (error) ->
      error = code: error.statusCode, message: error.message
      promise.done error, undefined

    client.write body
    client.end()

    promise

module.exports = Appnima
