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)

[((362, 391), 'flask.Blueprint', 'Blueprint', (['"""langid"""', '__name__'], {}), "('langid', __name__)\n", (371, 391), False, 'from flask import Blueprint\n'), ((1575, 1598), 'utils.utils.templated', 'templated', (['"""index.html"""'], {}), "('index.html')\n", (1584, 1598), False, 'from utils.utils import templated\n'), ((2410, 2434), 'utils.utils.templated', 'templated', (['"""langid.html"""'], {}), "('langid.html')\n", (2419, 2434), False, 'from utils.utils import templated\n'), ((1118, 1170), 'wtforms.BooleanField', 'BooleanField', (['"""Display raw sentences"""'], {'default': '(False)'}), "('Display raw sentences', default=False)\n", (1130, 1170), False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((1278, 1288), 'wtforms.widgets.TextArea', 'TextArea', ([], {}), '()\n', (1286, 1288), False, 'from wtforms.widgets import TextArea\n'), ((2168, 2214), 'flask.flash', 'flash', (["('Something went wrong %s' % e)", '"""danger"""'], {}), "('Something went wrong %s' % e, 'danger')\n", (2173, 2214), False, 'from flask import Flask, render_template, request, flash\n'), ((2223, 2243), 'logging.exception', 'logging.exception', (['e'], {}), '(e)\n', (2240, 2243), False, 'import logging\n'), ((2751, 2837), 'langid.lang_of_text', 'langid.lang_of_text', (['form.text.data'], {'model': 'form.model_class.data', 'with_proba': '(True)'}), '(form.text.data, model=form.model_class.data, with_proba\n    =True)\n', (2770, 2837), False, 'import langid\n'), ((478, 503), 'wtforms.validators.DataRequired', 'validators.DataRequired', ([], {}), '()\n', (501, 503), False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((505, 562), 'wtforms.validators.URL', 'validators.URL', ([], {'message': '"""Sorry, this is not a valid URL,"""'}), "(message='Sorry, this is not a valid URL,')\n", (519, 562), False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((657, 682), 'wtforms.validators.DataRequired', 'validators.DataRequired', ([], {}), '()\n', (680, 682), False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((684, 721), 'wtforms.validators.NumberRange', 'validators.NumberRange', ([], {'min': '(1)', 'max': '(20)'}), '(min=1, max=20)\n', (706, 721), False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((892, 917), 'wtforms.validators.DataRequired', 'validators.DataRequired', ([], {}), '()\n', (915, 917), False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((1072, 1097), 'wtforms.validators.DataRequired', 'validators.DataRequired', ([], {}), '()\n', (1095, 1097), False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((1310, 1335), 'wtforms.validators.DataRequired', 'validators.DataRequired', ([], {}), '()\n', (1333, 1335), False, 'from wtforms import StringField, validators, SelectField, BooleanField\n'), ((1490, 1515), 'wtforms.validators.DataRequired', 'validators.DataRequired', ([], {}), '()\n', (1513, 1515), False, 'from wtforms import StringField, validators, SelectField, BooleanField\n')]