 # hubot gerrit search <query> - Search Gerrit for changes - the query should follow the normal Gerrit query rules.
 # hubot gerrit (ignore|report) events for (project|user|event) <thing> - Tell Hubot how to report Gerrit events.
 #
+
+cp = require "child_process"
+url = require "url"
 
 # Required - The SSH URL for your Gerrit server.
 sshUrl = process.env.HUBOT_GERRIT_SSH_URL || ""

#   To disable event stream spam, use the value "disabled"
eventStreamRooms = process.env.HUBOT_GERRIT_EVENTSTREAM_ROOMS

cp = require "child_process"
url = require "url"

# Format JSON query result (see http://gerrit-documentation.googlecode.com/svn/Documentation/2.4/json.html#change)
formatQueryResult = (r) ->
  updated = new Date(r.lastUpdated * 1000).toDateString()
  "'#{r.subject}' for #{r.project}/#{r.branch} by #{extractName r} on #{updated}: #{r.url}"

# Format JSON event data (see http://gerrit-documentation.googlecode.com/svn/Documentation/2.4/cmd-stream-events.html)
formatEvent = (e) ->
  switch e.type
    when "patchset-created" then formatPatchsetEvent "New patchset", e
    when "change-abandoned" then formatPatchsetEvent "Patchset abandoned", e
    when "change-restored"  then formatPatchsetEvent "Patchset restored", e
    when "change-merged"    then formatPatchsetEvent "Patchset merged", e
    when "comment-added"    then formatPatchsetEvent "New comments", e
    when "ref-updated"      then "Ref updated - #{extractProject e}/#{e.refUpdate.refName} by #{extractName e}"
    else null

formatPatchsetEvent = (type, e) ->
  "#{type} - '#{e.change.subject}' for #{extractProject e}/#{e.change.branch} by #{extractName e}: #{e.change.url}"

# Format name given best available data. This tries to find an 'account' object
# given either a 'change' object or a gerrit event-stream object. See...
# - http://gerrit-documentation.googlecode.com/svn/Documentation/2.4/json.html#account
# - http://gerrit-documentation.googlecode.com/svn/Documentation/2.4/json.html#change
# - http://gerrit-documentation.googlecode.com/svn/Documentation/2.4/cmd-stream-events.html
extractName = (json) ->
  account = json.uploader || json.abandoner || json.restorer || json.submitter || json.author || json.owner
  account?.name || account?.email || "Gerrit"

extractProject = (json) -> (json.change || json.refUpdate).project

module.exports = (robot) ->
  gerrit = url.parse sshUrl


  isIgnored = (type, thing) -> (t for t in ignoresOfType robot, type when t is thing).length != 0
  isWanted = (event) -> !(
    isIgnored("project", (event.change || event.refUpdate).project) ||
    isIgnored("user", extractName event) ||
    isIgnored("event", event.type))

  streamEvents.stderr.on "data", (data) ->
    robot.logger.info "Gerrit stream-events: #{data}"
  streamEvents.stdout.on "data", (data) ->
    robot.logger.debug "Gerrit stream-events: #{data}"
    json = try
      JSON.parse data
    catch error
      robot.logger.error "Gerrit stream-events: Error parsing Gerrit JSON. Error=#{error}, Event=#{data}"
      null
    return unless json
    formatter = formatters.events[json.type]
    msg = try
      formatter json if formatter
    catch error
      robot.logger.error "Gerrit stream-events: Error formatting event. Error=#{error}, Event=#{data}"
      null
    if formatter == null
      robot.logger.info "Gerrit stream-events: Unrecognized event #{data}"
    else if msg && isWanted json
      # Bug in messageRoom? Doesn't work with multiple rooms
