 # Author:
 #   mxlje
 
-asana_api_key = process.env.HUBOT_ASANA_API_KEY
-asana_auth    = 'Basic ' + new Buffer("#{asana_api_key}:").toString('base64')
+asana_api_key     = process.env.HUBOT_ASANA_API_KEY
+asana_auth_header = 'Basic ' + new Buffer("#{asana_api_key}:").toString('base64')
 
 asana_task_endpoint = (task_id) ->
   "https://app.asana.com/api/1.0/tasks/#{task_id}"

asana_project_endpoint = (project_id) ->
  "https://app.asana.com/api/1.0/projects/#{project_id}"

# templates for response
task_response = (task) ->
  """
  > **#{task.status} #{task.title} (#{task.assignee})**
  > #{task.notes}
  """



get_task = (task_id, robot, msg) ->
  robot.http(asana_task_endpoint task_id)
    .header("Authorization", asana_auth)
    .get() (err, res, body) ->

      # basic error handling
      if err
       msg.send "Something went wrong: #{err}"
       return

      if res.statusCode != 200
       msg.send "Asana returned HTTP #{res.statusCode}: #{JSON.parse(body).errors[0].message}"
       return

       task.notes = "(no description)"

      # send the finished markdown down the pipe
      msg.send task_template(task)


get_project = (project_id, robot, msg) ->
  robot.http(asana_project_endpoint project_id)
    .header("Authorization", asana_auth_header)
    .get() (err, res, body) ->

      # Check for general networking errors
      if err
       msg.send "Something went wrong: #{err}"
       return

      # The request made to Asana was invalid
      if res.statusCode != 200
       msg.send "Asana returned HTTP #{res.statusCode}: #{JSON.parse(body).errors[0].message}"
       return

      # parse the response body
      data = JSON.parse(body).data

      # extract and reformat data from response
      project =
       name:      data.name
       workspace: data.workspace.name

      # clip notes at first paragraph
      if data.notes.length > 0
       split = data.notes.split("\n")
       project.notes = if split.length > 1 then "#{split[0]} …" else data.notes
      else
       project.notes = "(no description)"

      # send the finished markdown down the pipe
      msg.send project_template(project)


# listen for Asana deeplinks
