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

from datetime import datetime, timedelta
from flask import Response, request #@UnresolvedImport
from flaskext.sqlalchemy import get_debug_queries
from iri_tweet.models import TweetSource, Tweet
from pyrfc3339.generator import generate
from sqlalchemy import func, desc #@UnresolvedImport
from sqlalchemy.orm import joinedload
from tweetgserver import app, db, cache
import pytz
import simplejson as json #@UnresolvedImport
import re
import math

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', methods=['GET'])
def total():
    query = db.session.query(func.count(TweetSource.id)) #@UndefinedVariable
    ts_list_count = query.scalar()
    return jsonpwrap({"total":ts_list_count})

@app.route('/podium/<tokens>', methods=['GET'])
def podium(tokens):
    token_list = tokens.split(",")
    query_base = db.session.query(func.count(Tweet.id)) #@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)
    
