from flask import Flask, jsonify
from flask import render_template
from flask import request
from threading import Thread
import tweetminer

app = Flask(__name__)

fname = './tmp/liveStream.json'

global th
global score
global phrase
global finished

@app.route("/")
def init():
    return render_template('index.html')

@app.route("/", methods=['POST'])
def calc():
    global th
    global finished
    global score
    global phrase
    text = request.form['query']
    run_time = int(request.form['runtime'])
    finished = False
    phrase = text
    th = Thread(target=something, args=(text, run_time))
    th.start()
    # x = calculate(text, run_time)
    return render_template('loading.html', text=phrase, time=run_time)

@app.route("/result")
def result():
    global score
    global phrase
    search = phrase
    x = score
    return render_template('output.html', text=search, pop=x)

def something(phrase, time):
    global finished
    global score
    score = calculate(phrase, time)
    finished = True

@app.route("/status")
def status():
    global finished
    return jsonify(dict(status=('finished' if finished else 'running')))

def calculate(text, runTime):
    auth, api = tweetminer.get_credentials()
    tweetminer.get_live_tweets(auth, text, fname=fname, runTime=runTime)
    x = tweetminer.get_popularity(runTime=runTime, fname=fname)
    return x

if __name__ == "__main__":
    global th
    global phrase
    global score
    global finished
    app.run(debug=True)

@@ -194,60 +194,57 @@
 n'%0A%0A
-global th%0Aglobal score%0Aglobal phrase%0Aglobal finished
+th = None%0Ascore = -1%0Aphrase = %22%22%0Afinished = False
 %0A%0A@a
@@ -762,77 +762,8 @@
 ():%0A
-    global score%0A    global phrase%0A    search = phrase%0A    x = score%0A
     
@@ -809,21 +809,25 @@
 ext=
-search
+phrase
 , pop=
-x
+score
 )%0A%0Ad
@@ -839,22 +839,20 @@
 mething(
-phrase
+text
 , time):
@@ -911,22 +911,20 @@
 lculate(
-phrase
+text
 , time)%0A
@@ -1331,77 +1331,8 @@
 _%22:%0A
-    global th%0A    global phrase%0A    global score%0A    global finished%0A
     

Fix global variables