 #
 # <thing>++ - give thing some karma
 # <thing>-- - take away some of thing's karma
-# karma <thing> - check thing's karma, if <thing> is omitted get top and bottom 3
+# karma <thing> - check thing's karma (if <thing> is omitted, show the top 5)
 # karma empty <thing> - empty a thing's karma
+# karma best - show the top 5
+# karma worst - show the bottom 5
 class Karma
   
   constructor: (@robot) ->

    k = if @cache[thing] then @cache[thing] else 0
    return k

  summary: ->
    s = []
    for key,val of @cache
      s.push({name: key, karma: val})
    s.sort (a,b) -> b.karma - a.karma
    if s.length >= 6
      return [s[0], s[1], s[2], s[s.length-3], s[s.length-2], s[s.length-1]]
    else
      return s

module.exports = (robot) ->
  karma = new Karma robot
  robot.hear /(\S+[^+\s])\+\+(\s|$)/, (msg) ->

    karma.kill subject
    msg.send "#{subject} has had its karma scattered to the winds."
  
  robot.respond /karma( best)?$/i, (msg) ->
    verbiage = ["The Best"]
    for item, rank in karma.top()
      verbiage.push "#{rank + 1}. #{item.name} - #{item.karma}"
    msg.send verbiage.join("\n")
      
  robot.respond /karma worst$/i, (msg) ->
    verbiage = ["The Worst"]
    for item, rank in karma.bottom()
      verbiage.push "#{rank + 1}. #{item.name} - #{item.karma}"
    msg.send verbiage.join("\n")
  
  robot.respond /karma (\S+[^-\s])$/i, (msg) ->
    match = msg.match[1].toLowerCase()
    if match != "best" && match != "worst"
      msg.send "\"#{match}\" has #{karma.get(match)} karma."
  