 # Todo:
 # - Save favourites?
 
+#
+# Config
+#
+TWITCH_MAX_RESULTS = 5
+TWITCH_STORAGE_KEY = process.env.HUBOT_TWITCH_KEY or "_twitch"
+
 module.exports = (robot) ->
-    maxResults = 5
-
-    twitchData = ->
-        robot.brain.data.twitch or= {}
+    GetTTVData = ->
+        robot.brain.data[TWITCH_STORAGE_KEY] or= {}
 
     robot.respond /ttv fav/i, (msg) ->
         return

            msg.send "Viewers: #{object.stream.viewers}"

    robot.respond /ttv top/i, (msg) ->
        createURL = (game) ->
            "http://www.twitch.tv/directory/game/#{encodeURIComponent(game)}"

        twitchRequest msg, "/games/top", limit: maxResults, (object) ->
            for gameObj, i in object.top
                msg.send "#{i + 1}. #{gameObj.game.name} | Viewers: #{gameObj.viewers} | Channels: #{gameObj.channels} | #{createURL(gameObj.game.name)}"

twitchRequest = (msg, api, params = {}, handler) ->
    msg.http("https://api.twitch.tv/kraken#{api}")
        .query(params)
        .get() (err, res, body) ->

        return

    robot.respond /ttv featured/i, (msg) ->
        GetTwitchResult msg, '/streams/featured', null, (object) ->
            for feature in object.featured
                channel = feature.stream.channel
                msg.send "#{feature.stream.game}: #{channel.display_name} (#{channel.status}) - #{channel.url} [Viewers: #{feature.stream.viewers}]"

    robot.respond /ttv game (.+)/i, (msg) ->
        category = msg.match[1]
        GetTwitchResult msg, '/streams', { game: category }, (object) ->
            if object._total is 0
                msg.reply "No live streams were found in \"#{category}\". Try a different category or try again later."
                return
