 pagerduty = require('./pagerduty/pagerduty')
 pdServiceEmail = process.env.HUBOT_INCIDENT_PAGERDUTY_SERVICE_EMAIL
 pdTestEmail = process.env.HUBOT_PAGERDUTY_TEST_EMAIL
+incidentRoom              = process.env.HUBOT_INCIDENT_PAGERDUTY_ROOM
+# Webhook listener endpoint. Set it to whatever URL you want, and make sure it matches your pagerduty service settings
+incidentEndpoint          = process.env.HUBOT_INCIDENT_PAGERDUTY_ENDPOINT || "/incident"
+
 
 module.exports = (robot) ->
   unless robot.brain.data.openincidents?
     robot.brain.data.openincidents = {}
 
-  # This is invoked by the Slack/Hubot integration here:
-  # * https://slack.com/apps/A0F81FMQW-pagerduty
-  # * https://www.pagerduty.com/docs/guides/slack-integration-guide/
-  robot.hear /Triggered: Incident #(\d+) \(([A-Z0-9]+)\)/, (msg) ->
-    # TODO: work on auth so only the PagerDuty bot is responded to
+  if incidentEndpoint && incidentRoom
+    robot.router.post incidentEndpoint, (req, res) ->
+      robot.messageRoom(incidentRoom, parseWebhook(req,res))
+      res.end()
+
+  robot.respond /start (\d+)/i, (msg) ->
+    # TODO: work on auth so only the specified users are responded to
     incidentNumber = msg.match[1]
-    incidentHash = buildIncidentHash(incidentNumber,msg.match[2])
-    robot.brain.data.openincidents[incidentNumber] = incidentHash
-    msg.send "INCIDENT NOTIFY: Incident #{incidentNumber} has been started"
-    msg.emote "Bot has started logging all conversation in this room as of #{robot.brain.data.openincidents[incidentNumber]['start_time']}"
-    checklists.getChecklist 'start', (err, content) ->
-      if err?
-        robot.emit 'error', err, msg
-        return
-      msg.send formatMarkDown(content)
+    startIncident(incidentNumber, msg)
 
   # helper function to show this works, should be removed when debugging is done
   #robot.respond /incident log (\d+)/i, (msg) ->
   #  incidentHash = robot.brain.data.openincidents[msg.match[1]]
   #  msg.send incidentHash['log']
 
-  robot.hear /Resolved: Incident #(\d+) \(([A-Z0-9]+)\)/, (msg) ->
-    # TODO: work on auth so only the PagerDuty bot is responded to
+  robot.respond /incident currently tracking/i, (msg) ->
+    for k,v of robot.brain.data.openincidents
+      msg.emote "Currently tracking PagerDuty Incident #{k} from start time #{robot.brain.data.openincidents[k]['log']}"
+
+  robot.respond /end (\d+)/i, (msg) ->
+    # TODO: work on auth so only authorized users are responded to
     incidentNumber = msg.match[1]
-    incidentHash = robot.brain.data.openincidents[incidentNumber]
-    incidentHash['end_time'] = getCurrentTime()
-    duration = calculateDuration(incidentHash['start_time'],incidentHash['end_time'])
-    postNoteToPagerDuty(msg, incidentNumber, incidentHash)
-    msg.send "INCIDENT NOTIFY: Resolved incident #{incidentNumber}, Incident duration #{duration}"
-    checklists.getChecklist 'end', (err, content) ->
-      if err?
-        robot.emit 'error', err, msg
-        return
-      msg.send formatMarkDown(content)
-
-    delete robot.brain.data.openincidents[incidentNumber]
+    endIncident(incident_number, msg)
   
   robot.respond /incident help/i, (msg) ->
     commands = robot.helpCommands()
     commands = (command for command in commands when command.match(/incident/))
     msg.send commands.join("\n")
 
+  ## TODO: ensure only get the messages from the incident room
   robot.hear /(.+)/, (msg) ->
     for k,v of robot.brain.data.openincidents
       robot.brain.data.openincidents[k]['log'] += "#{getCurrentTime()}  #{msg.message.user.name} #{msg.message.text} \n"
 
-  buildIncidentHash = (incidentNumber, urlId) ->
-    #robot.brain.data.openincidents[incidentNumber] = {}
-    #incidentHash = robot.brain.data.openincidents[incidentNumber]
+  ##### Functions
+
+  # TODO: find a way to remove 'msg'
+  startIncident = (incidentNumber, msg) ->
+    #is inicident being tracked yet?
+    for k,v of robot.brain.data.openincidents
+      if k == incidentNumber
+        mrobot.messageRoom(incidentRoom, "incident #{k} is already being tracked")
+        return
+    incidentHash = buildIncidentHash(incidentNumber)
+    robot.brain.data.openincidents[incidentNumber] = incidentHash
+    robot.messageRoom(incidentRoom, "INCIDENT NOTIFY: Incident #{incidentNumber} has been started")
+    robot.messageRoom(incidentRoom, "Bot has started logging all conversation in this room as of #{robot.brain.data.openincidents[incidentNumber]['start_time']}")
+    checklists.getChecklist 'start', (err, content) ->
+      if err?
+        robot.emit 'error', err, msg
+        return
+      msg.send formatMarkDown(content)
+
+  # TODO: find a way to remove 'msg'
+  endIncident = (incidentNumber, msg) ->
+    incidentHash = robot.brain.data.openincidents[incidentNumber]
+    incidentHash['end_time'] = getCurrentTime()
+    duration = calculateDuration(incidentHash['start_time'],incidentHash['end_time'])
+    #postNoteToPagerDuty(msg, incidentNumber, incidentHash)
+    msg.send "INCIDENT NOTIFY: Resolved incident #{incidentNumber}, Incident duration #{duration}"
+    checklists.getChecklist 'end', (err, content) ->
+      if err?
+        robot.emit 'error', err, msg
+        return
+      msg.send formatMarkDown(content)
+
+    delete robot.brain.data.openincidents[incidentNumber]
+
+  buildIncidentHash = (incidentNumber) ->
     incidentHash = {}
     incidentHash['start_time'] = getCurrentTime()
     incidentHash['end_time'] = ""
-    incidentHash['url'] = urlId
     incidentHash['log'] = ""
     incidentHash
 

          else
            msg.send "Sorry, could not add transcript of room to PagerDuty as note."

  calculateDuration = (start, end) ->
    Math.floor(moment.duration(moment(end,"YYYYMMDDTHHmmss").diff(moment(start,"YYYYMMDDTHHmmss"))).asHours())+moment.utc(moment(end,"YYYYMMDDTHHmmss").diff(moment(start,"YYYYMMDDTHHmmss"))).format(":mm:ss")
  

    block += "```\n"
    block

  ##### Pager Duty interaction
  getPagerDutyServiceUser = (msg, required, cb) ->
    if typeof required is 'function'
      cb = required
