from flask import (
    abort,
    flash,
    redirect,
    render_template,
    request,
    url_for
)
from flask_login import current_user, login_user, login_required, logout_user
from app import db
from app.email import create_message, send
from app.models import User
from . import bp
from .forms import (
    LoginForm,
    ResetPasswordForm,
    ResetPasswordRequestForm,
    RegistrationForm
)


@bp.before_app_request
def before_request():
    """
    Checks if a user is unconfirmed when visiting specific sites. Redirects to
    unconfirmed view if user is unconfirmed.
    """
    if current_user.is_authenticated:
        current_user.ping()
        db.session.commit()
        if (not current_user.confirmed
                and request.endpoint
                and request.blueprint != 'auth'
                and request.endpoint != 'static'):
            return redirect(url_for('auth.unconfirmed'))


@bp.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('main.dashboard'))
    form = RegistrationForm(prefix='registration-form')
    if form.validate_on_submit():
        try:
            user = User.create(
                email=form.email.data.lower(),
                password=form.password.data,
                username=form.username.data
            )
        except OSError:
            flash('Internal Server Error', category='error')
            abort(500)
        flash(f'User "{user.username}" created')
        token = user.generate_confirm_token()
        msg = create_message(
            user.email,
            'Confirm Your Account',
            'auth/email/confirm',
            token=token,
            user=user
        )
        send(msg)
        flash('A confirmation email has been sent to you by email')
        db.session.commit()
        return redirect(url_for('.login'))
    return render_template(
        'auth/register.html.j2',
        form=form,
        title='Register'
    )


@bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('main.dashboard'))
    form = LoginForm(prefix='login-form')
    if form.validate_on_submit():
        user = User.query.filter((User.email == form.user.data.lower()) | (User.username == form.user.data)).first()
        if user and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            next = request.args.get('next')
            if next is None or not next.startswith('/'):
                next = url_for('main.dashboard')
            flash('You have been logged in')
            return redirect(next)
        flash('Invalid email/username or password', category='error')
    return render_template('auth/login.html.j2', form=form, title='Log in')


@bp.route('/logout')
@login_required
def logout():
    logout_user()
    flash('You have been logged out')
    return redirect(url_for('main.index'))


@bp.route('/unconfirmed')
@login_required
def unconfirmed():
    if current_user.confirmed:
        return redirect(url_for('main.dashboard'))
    return render_template('auth/unconfirmed.html.j2', title='Unconfirmed')


@bp.route('/confirm')
@login_required
def confirm_request():
    if current_user.confirmed:
        return redirect(url_for('main.dashboard'))
    token = current_user.generate_confirm_token()
    msg = create_message(
        current_user.email,
        'Confirm Your Account',
        'auth/email/confirm',
        token=token,
        user=current_user
    )
    send(msg)
    flash('A new confirmation email has been sent to you by email')
    return redirect(url_for('.unconfirmed'))


@bp.route('/confirm/<token>')
@login_required
def confirm(token):
    if current_user.confirmed:
        return redirect(url_for('main.dashboard'))
    if current_user.confirm(token):
        db.session.commit()
        flash('You have confirmed your account')
        return redirect(url_for('main.dashboard'))
    flash('The confirmation link is invalid or has expired', category='error')
    return redirect(url_for('.unconfirmed'))


@bp.route('/reset_password', methods=['GET', 'POST'])
def reset_password_request():
    if current_user.is_authenticated:
        return redirect(url_for('main.dashboard'))
    form = ResetPasswordRequestForm(prefix='reset-password-request-form')
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data.lower()).first()
        if user is not None:
            token = user.generate_reset_password_token()
            msg = create_message(
                user.email,
                'Reset Your Password',
                'auth/email/reset_password',
                token=token,
                user=user
            )
            send(msg)
        flash(
            'An email with instructions to reset your password has been sent '
            'to you'
        )
        return redirect(url_for('.login'))
    return render_template(
        'auth/reset_password_request.html.j2',
        form=form,
        title='Password Reset'
    )


@bp.route('/reset_password/<token>', methods=['GET', 'POST'])
def reset_password(token):
    if current_user.is_authenticated:
        return redirect(url_for('main.dashboard'))
    form = ResetPasswordForm(prefix='reset-password-form')
    if form.validate_on_submit():
        if User.reset_password(token, form.password.data):
            db.session.commit()
            flash('Your password has been updated')
            return redirect(url_for('.login'))
        return redirect(url_for('main.index'))
    return render_template(
        'auth/reset_password.html.j2',
        form=form,
        title='Password Reset',
        token=token
    )
