import json
import time
import urllib
import urllib2

from flask import render_template

from twitch_browser import app
from twitch_browser import twitch_stream


@app.route('/')
def index():
    games = ['Dota 2', 'StarCraft II: Heart of the Swarm', 'Dark Souls']
    streams = getGameStreams(games)
    return render_template("index.html", streams=streams)

@app.errorhandler(500)
def handleError(exc):
    app.logger.exception(exc)
    return render_template("error.html")

def getGameStreams(game_names):
    query = buildQuery(game_names)
    raw_content = fetchStreams(query)
    return parseStreams(raw_content)


def buildQuery(game_names):
    q = ''
    first = True
    for game_name in game_names:
        if first:
            first = False
        else:
            q += ' OR '
        q += '"%s"' % game_name
    return q


def fetchStreams(query):
    start = time.time()
    host = "https://api.twitch.tv"
    path = "/kraken/search/streams"
    params = urllib.urlencode({
        'q': query,
        'limit': 50,
        })
    url = "%s%s?%s" % (host, path, params)
    headers = {
        'Accept': 'application/vnd.twitchtv.v2+json',
        'Client-ID': 'Twitch Browser https://github.com/jachien/twitch-browser'
    }
    req = urllib2.Request(url, headers=headers)
    resp = urllib2.urlopen(req)
    content = resp.read()
    tot_time = time.time() - start
    app.logger.info('took %f secs to retrieve %s @ %s' % (tot_time, query, url))
    return content


def parseStreams(raw_content):
    streams = []
    streams_root = json.loads(raw_content)
    for stream in streams_root['streams']:
        streams.append(twitch_stream.TwitchStream(stream))
    return streams
@@ -80,16 +80,25 @@
 template
+, request
 %0A%0Afrom t
@@ -210,68 +210,18 @@
 s = 
-%5B'Dota 2', 'StarCraft II: Heart of the Swarm', 'Dark Souls'%5D
+getGames()
 %0A   
@@ -230,28 +230,32 @@
 treams = get
-Game
+Combined
 Streams(game
@@ -320,484 +320,576 @@
 s)%0A%0A
-@app.errorhandler(500)%0Adef handleError(exc):%0A    app.logger.exception(exc)%0A    return render_template(%22error.html%22)%0A%0Adef getGameStreams(game_names):%0A    query = buildQuery(game_names)%0A    raw_content = fetchStreams(query)%0A    return parseStreams(raw_content)%0A%0A%0Adef buildQuery(game_names):%0A    q = ''%0A    first = True%0A    for game_name in game_names:%0A        if first:%0A            first = False%0A        else:%0A            q += ' OR '%0A        q += '%22%25s%22' %25 game_name%0A    return q
+%0Adef getGames():%0A    games_cookie = request.cookies.get('games')%0A    if games_cookie is None:%0A        return %5B'Dota 2', 'StarCraft II: Heart of the Swarm', 'Dark Souls'%5D%0A    encoded_games = games_cookie.split(':')%0A    return %5Burllib.unquote(encoded_game).decode('utf8') for encoded_game in encoded_games%5D%0A%0A%0Adef getCombinedStreams(game_names):%0A    streams = %5B%5D%0A    for game_name in game_names:%0A        raw_content = fetchStreams(game_name)%0A        streams += parseStreams(raw_content)%0A    return sorted(streams, key=lambda stream: stream.getViewerCount(), reverse=True)
 %0A%0A%0Ad
@@ -904,21 +904,20 @@
 Streams(
-query
+game
 ):%0A    s
@@ -994,15 +994,8 @@
 ken/
-search/
 stre
@@ -1044,17 +1044,19 @@
    '
-q': query
+game': game
 ,%0A  
@@ -1497,13 +1497,12 @@
 me, 
-query
+game
 , ur
@@ -1729,16 +1729,135 @@
   return streams
+%0A%0A%0A@app.errorhandler(500)%0Adef handleError(exc):%0A    app.logger.exception(exc)%0A    return render_template(%22error.html%22)%0A

switch to using /streams?game= for individual queries, seems like it's the best we can do until twitch adds lookup by game id and allows multiple in one query