import logging

from flask import Blueprint

from flask import Flask, render_template, request, flash
from flask_wtf import FlaskForm
from wtforms import StringField, validators, SelectField, BooleanField
from wtforms.fields.html5 import IntegerRangeField
from wtforms.widgets import TextArea

import langid
from utils.utils import templated

blueprint_langid = Blueprint('langid', __name__)


class UrlForm(FlaskForm):
    url = StringField(
        'URL',
        validators=[validators.DataRequired(), validators.URL(message='Sorry, this is not a valid URL,')])

    wMin = IntegerRangeField(
        'Min. words',
        default=5,
        validators=[validators.DataRequired(), validators.NumberRange(min=1, max=20)])

    extractor_class = SelectField(
        'Extractor',
        default=langid.EXTRACTORS[0],
        choices=[(i, i) for i in langid.EXTRACTORS],
        validators=[validators.DataRequired()])

    model_class = SelectField(
        'Model',
        default=langid.MODELS[0],
        choices=[(i, i) for i in langid.MODELS],
        validators=[validators.DataRequired()])

    return_raw = BooleanField(
        'Display raw sentences',
        default=False
    )


class TextForm(FlaskForm):

    text = StringField(
        'Text',
        widget=TextArea(),
        validators=[validators.DataRequired()])

    model_class = SelectField(
        'Model',
        default=langid.MODELS[0],
        choices=[(i, i) for i in langid.MODELS],
        validators=[validators.DataRequired()])


@blueprint_langid.route('/', methods=['GET', 'POST'])
@templated('index.html')
def crawl():
    form = UrlForm(request.form)

    if request.method == 'GET':
        return dict(form=form)
    elif not form.validate():
        for f, errs in form.errors.items():
            flash("%s: %s" % (f, "<br>".join(errs)), 'danger')
        return dict(form=form)

    try:
        results = langid.mixed_sentences_from_urls(
            form.url.data.strip(), extractor_name=form.extractor_class.data, model=form.model_class.data,
            with_proba=True, min_words=form.wMin.data, return_raw=form.return_raw.data)
    except Exception as e:
        flash('Something went wrong %s' % e, 'danger')
        logging.exception(e)
        return dict(form=form)
    return dict(form=form, results=results, labels=langid.DEFAULT_LABELS)


@blueprint_langid.route('/text', methods=['GET', 'POST'])
@templated('langid.html')
def predict_text():
    form = TextForm(request.form)

    if request.method == 'GET':
        return dict(form=form)

    elif not form.validate():
        for f, errs in form.errors.items():
            flash("%s: %s" % (f, "<br>".join(errs)), 'danger')
        return dict(form=form)

    results = [[r] for r in langid.lang_of_text(
        form.text.data, model=form.model_class.data, with_proba=True)]
    return dict(form=form, results=results, labels=langid.DEFAULT_LABELS)

[((14, 19, 14, 48), 'flask.Blueprint', 'Blueprint', ({(14, 29, 14, 37): '"""langid"""', (14, 39, 14, 47): '__name__'}, {}), "('langid', __name__)", False, 'from flask import Blueprint\n'), ((60, 1, 60, 24), 'utils.utils.templated', 'templated', ({(60, 11, 60, 23): '"""index.html"""'}, {}), "('index.html')", False, 'from utils.utils import templated\n'), ((83, 1, 83, 25), 'utils.utils.templated', 'templated', ({(83, 11, 83, 24): '"""langid.html"""'}, {}), "('langid.html')", False, 'from utils.utils import templated\n'), ((39, 17, 42, 5), 'wtforms.BooleanField', 'BooleanField', (), '', False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((49, 15, 49, 25), 'wtforms.widgets.TextArea', 'TextArea', ({}, {}), '()', False, 'from wtforms.widgets import TextArea\n'), ((76, 8, 76, 54), 'flask.flash', 'flash', ({(76, 14, 76, 43): "('Something went wrong %s' % e)", (76, 45, 76, 53): '"""danger"""'}, {}), "('Something went wrong %s' % e, 'danger')", False, 'from flask import Flask, render_template, request, flash\n'), ((77, 8, 77, 28), 'logging.exception', 'logging.exception', ({(77, 26, 77, 27): 'e'}, {}), '(e)', False, 'import logging\n'), ((95, 28, 96, 69), 'langid.lang_of_text', 'langid.lang_of_text', (), '', False, 'import langid\n'), ((20, 20, 20, 45), 'wtforms.validators.DataRequired', 'validators.DataRequired', ({}, {}), '()', False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((20, 47, 20, 104), 'wtforms.validators.URL', 'validators.URL', (), '', False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((25, 20, 25, 45), 'wtforms.validators.DataRequired', 'validators.DataRequired', ({}, {}), '()', False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((25, 47, 25, 84), 'wtforms.validators.NumberRange', 'validators.NumberRange', (), '', False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((31, 20, 31, 45), 'wtforms.validators.DataRequired', 'validators.DataRequired', ({}, {}), '()', False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((37, 20, 37, 45), 'wtforms.validators.DataRequired', 'validators.DataRequired', ({}, {}), '()', False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((50, 20, 50, 45), 'wtforms.validators.DataRequired', 'validators.DataRequired', ({}, {}), '()', False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((56, 20, 56, 45), 'wtforms.validators.DataRequired', 'validators.DataRequired', ({}, {}), '()', False, 'from wtforms import StringField, validators, SelectField, BooleanField\n')]