 module.exports = (robot) ->
   statusEmoji = new StatusEmoji
 
+  brewing = {}
+  robot.brain.on 'loaded', =>
+    robot.brain.data.coffee ?= { brewing: {} }
+    brewing = robot.brain.data.coffee.brewing ?= {}
+
+  coffeeconomy = new Coffeeconomy robot
+
   robot.respond /coffee (\d+)$/i, (msg) ->
     cups = msg.match[1]
 

      dibs: [barista],
      messageMetadata: msg.envelope.message.metadata,

    msg.send "@team Brew started by @#{brewing.barista}! #{statusEmoji.random('success')}\n" +
      "To grab a spot use: #{robot.alias}dibs\n" +
      "To end the brew use: #{robot.alias}fresh pot"


    msg.send "You need #{scoops} level scoops and #{water} L of water."

  robot.respond /(?::coffee:|☕️) balance(?:\s+@?([^ ]+)\s*)?$/i, (msg) ->
    clientName = msg.match[1] || msg.message.user.name
    client = robot.brain.usersForRawFuzzyName(clientName)[0]

    if not client
      msg.send "Sorry, I don't know anyone named #{clientName}! #{statusEmoji.random('failure')}"
      return

    if not coffeeconomy.hasAccount client
      msg.send "#{client.name} hasn't opened an account by `#{robot.alias}brewing` or `#{robot.alias}dibs`ing yet! #{statusEmoji.random('failure')}"
      return
    msg.send coffeeconomy.accountFormatter coffeeconomy.account client

  robot.respond /(?::coffee:|☕️) top(?:\s+(\d+))?$/i, (msg) ->
    limit = parseInt msg.match[1]?.trim() || 10
    count = 1
    msg.send "These are the top :coffee: accounts:\n" +
        (coffeeconomy.topListEntryFormatter count++, account for account in coffeeconomy.top limit).join("\n")

  robot.respond /(?::coffee:|☕️) bottom(?:\s+(\d+))?$/i, (msg) ->
    limit = parseInt msg.match[1]?.trim() || 10
    total = coffeeconomy.length()

    msg.send "These are the bottom :coffee: accounts:\n" +
        (coffeeconomy.topListEntryFormatter total--, account for account in coffeeconomy.bottom limit).join("\n")

  robot.respond /brewing\s*$/i, (msg) ->
    if isBrewing()
