#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Response, request #@UnresolvedImport
from flaskext.sqlalchemy import get_debug_queries
from iri_tweet.models import TweetSource, Tweet
from sqlalchemy import func #@UnresolvedImport
from tweetgserver import app, db
from datetime import datetime
import simplejson as json #@UnresolvedImport

def jsonpwrap(resobj):
    resp_str = json.dumps(resobj)
    callback_param = request.args.get("callback")
    if callback_param:
        resp_str = "%s( %s );" % (callback_param, resp_str)
        mime_type = 'text/javascript'
    else:
        mime_type = 'application/json'
    return Response(resp_str, mimetype=mime_type)

@app.route('/', methods=['GET'])
def index():
    query = db.session.query(func.count(TweetSource.id)) #@UndefinedVariable
    ts_list_count = query.scalar()
    return 'Nb of tweets ' + str(ts_list_count)

@app.route('/total/<int:since>', methods=['GET'])
def total(since):
    sincetime = datetime.fromtimestamp(since - 3600) # Hack rapide car les horaires sont enregistres en mode naif dans la bdd
    delta_td = datetime.now() - sincetime
    delta_s = delta_td.total_seconds()
    query = db.session.query(func.count(Tweet.id)).filter(Tweet.created_at >= sincetime) #@UndefinedVariable
    ts_list_count = query.scalar()
    res = {
           "total" : ts_list_count,
           "delta": int(delta_s),
           "tweets_per_minute": 60. * ts_list_count / delta_s
           }
    return jsonpwrap(res)

@app.route('/podium/<int:since>/<tokens>', methods=['GET'])
def podium(since, tokens):
    sincetime = datetime.fromtimestamp(since - 3600) # Hack rapide car les horaires sont enregistres en mode naif dans la bdd
    token_list = tokens.split(",")
    query_base = db.session.query(func.count(Tweet.id)).filter(Tweet.created_at >= sincetime)  #@UndefinedVariable
    podium_res = {}
    for token in token_list:
        query = query_base.filter(Tweet.text.op('~*')(token)) #@UndefinedVariable
        podium_res[token] = query.scalar()
    res = {
        "podium" : podium_res,
        "total" : query_base.scalar()
    }
    return jsonpwrap(res)
    
