 #   HUBOT_PAGERDUTY_SUBDOMAIN
 #   
 # Commands:
-#   hubot incident start - Initiate incident
-#   hubot incident end - Resolve incident
+#   hubot incident start <pagerduty id> - Manually initiate incident
+#   hubot incident end <pagerduty id> - Manually resolve incident
+#   hubot incident currently tracking - List out the incidents currently being tracked in the hubot brain
 #
 # Notes:
 #   <optional notes required for the script>

    block += "```\n"
    block

  getPagerDutyServiceUser = (msg, required, cb) ->
    if typeof required is 'function'
      cb = required

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 = {}

  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]
    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.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]
    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"

  ##### 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['log'] = ""
    incidentHash

