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

import json, urllib
from unicodedata import normalize

from StringIO import StringIO

from text import *
from query import *
from question import *

from functools import wraps
from flask import Flask, request, jsonify, current_app, Response, make_response, render_template
from flask.ext.bootstrap import Bootstrap

app = Flask(__name__)
Bootstrap(app)

def jsonp(func):
    """Wraps JSONified output for JSONP requests."""
    @wraps(func)
    def decorated_function(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            data = str(func(*args, **kwargs))
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype)
        else:
            return func(*args, **kwargs)
    return decorated_function


@app.route("/answer")
def audioproxy():

    answer = unicode(request.args.get('a'))
    #answer = unicode(urllib.unquote(answer))
    #answer = normalize('NFKD', answer).encode('ASCII','ignore')
    
    url = "http://translate.google.com/translate_tts?tl=pt_br&q=%s&ie=UTF-8" % answer
    headers = {
        'User-Agent': '',
        'From': ''
    }
    audio = requests.get(url, headers=headers)
    buf = StringIO()
    buf.write(audio.content)
    response = make_response(buf.getvalue())
    buf.close()
    response.headers['Content-Type'] = 'audio/mpeg'
    response.headers['Content-Disposition'] = 'attachment; filename=sound.mp3'
    return response


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


@app.route("/info", methods=["POST"])
def info():

    template = """
        <html><body>
        <audio controls="controls" autoplay="autoplay" style="display:none;">
            <source id="a" src="/answer?a=[ANSWER]" />
        </audio>
        </body></html>
    """

    question = unicode(request.form.get("question"))
    latitude = float(request.form.get("lt"))
    longitude = float(request.form.get("ll"))
    
    if not question or not latitude or not longitude:
        return "Erro"
    
    nltk.data.path.append('./nltk_data/')
    data = get_named_entities(question)   

    if not data:
        data = question
    
    question_type = identify_question(question)
    bus = best_match(question)
    
    if question_type == 'time':
        try:
            answer = next_bus_arrival_time(bus, latitude, longitude)
        except Exception as e:
            answer = e.message
    
    elif question_type == 'location':
        answer = 'loc'
    
    else: 
        answer = 'Desculpe, não consegui entender o que você precisa.'

    return template.replace('[ANSWER]', answer)

if __name__ == "__main__":
    app.run(debug=True)
