 asana_api_key     = process.env.HUBOT_ASANA_API_KEY
 asana_auth_header = 'Basic ' + new Buffer("#{asana_api_key}:").toString('base64')
 
+# Listen for Asana deeplinks
+module.exports = (robot) ->
+  robot.hear /app\.asana\.com\/\d{1}\/\d+\/(\d+)/i, (msg) ->
+    id = msg.match[1]
+
+    # Check for a task first
+    get_task id, robot, msg, (task) ->
+      if task.statusCode == 403
+        # on 403 status check for project
+        get_project id, robot, msg, (project) ->
+          msg.send project_template(project)
+
+      else
+        msg.send task_template(task)
+
+
+
 # Helpers for Asana endpoint URLs
 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}"

# (Markdown) templates for responses based on response type
task_template = (task) ->
  """
  > **#{task.status} #{task.title} (#{task.assignee})**
  > #{task.notes}
  """

project_template = (project) ->
  """
  > **#{project.name} (#{project.workspace})**
  > #{project.notes}
  """

report_error = (msg, err) ->
  msg.send "Something went wrong: #{err}"


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

        return

      # If Asana returns 403 Forbidden it is possible that the URL belongs to
      # a project instead of a task. We call back with a task object containing
      # the 403 status so the callback can start a new query
      task = {}
      if res.statusCode == 403
        task.statusCode = 403
        cb task
        return

      if res.statusCode != 200
        report_invalid_request msg, res, body
        return

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

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