from flask import Blueprint, render_template, redirect, url_for, jsonify, abort, flash, current_app
from flask_login import login_user, current_user, login_required
from sqlalchemy.exc import IntegrityError

from .. import db
from ..models import Category, Sensor, Subview, View, ChartConfig, User
from ..queries import query_get_category_by_id, query_get_sensor_by_id, query_get_subview_by_id, query_get_view_by_id, \
    query_get_user_by_id, query_get_user_by_name, query_get_chartconfig_by_id
from ..forms import CategoryForm, SensorForm, SubviewForm, ViewForm, UserForm, LoginForm
from ..utils import send_email
from ..decorators import check_confirmed

forms = Blueprint('forms', __name__)

@forms.route('/forms/login', methods=['GET', 'POST'])
def login_form():
    form = LoginForm()
    if form.validate_on_submit():
        user = query_get_user_by_name(form.username.data)
        if user is None:
            abort(400)
        if not user.confirmed:
            flash('Please activate your account!', 'warning')
            return redirect(url_for('main.index'))
        if user.verify_password(form.password.data):
            login_user(user)
            return redirect(url_for('main.userpage', user_slug=user.user_slug))
    return render_template('form.html.j2', title='Login', url=url_for('forms.login_form'), form=form, cta='Login')

@forms.route('/forms/users/add', methods=['GET', 'POST'])
def add_user_form():
    form = UserForm()
    if form.validate_on_submit():
        user = User()
        form.populate_obj(user)
        db.session.add(user)
        try:
            db.session.commit()
            token = user.generate_confirmation_token()
            url = url_for('main.confirm_email', token=token, _external=True)
            send_email(to=user.email, subject='Confirm Your Account', body=render_template('activate.html.j2', url=url))
        except IntegrityError:
            db.session.rollback()
        login_user(user)
        return redirect(url_for('main.index'))
    return render_template('form.html.j2', title='Sign Up', url=url_for('forms.add_user_form'), form=form, cta='Sign Up')

@forms.route('/forms/users/edit', methods=['GET', 'POST'])
@login_required
@check_confirmed
def edit_user_form():