import functools

from flask import (
    Blueprint, current_app, g, flash, redirect, url_for, session,
    render_template
)
from werkzeug.security import check_password_hash

from flask_wtf import FlaskForm
from wtforms import ValidationError, PasswordField, SubmitField
from wtforms.validators import InputRequired


bp = Blueprint('auth', __name__)

class LoginForm(FlaskForm):
    @staticmethod
    def validate_password(form, field) -> None:
        if not field.data:
            raise ValidationError("Please enter a password.")
        if not check_password_hash(current_app.config['ADMIN_PASSWORD'], field.data):
            raise ValidationError("Invalid password.")

    password = PasswordField(
        'Password',
        [InputRequired('Please enter a password.'), validate_password],
    )

    submit = SubmitField(
        'Log In',
    )

@bp.route("/login", methods=("GET", "POST"))
def login():
    form = LoginForm()
    if form.validate_on_submit():
        session.clear()
        session['is_authenticated'] = True
        return redirect(url_for('index'))

    return render_template('auth/login.html', form=form)


@bp.before_app_request
def load_logged_in_user():
    authentication_status = session.get('is_authenticated')
    if authentication_status:
        g.is_authenticated = authentication_status
    else:
        g.is_authenticated = False


@bp.route('/logout')
def logout():
    session.clear()
    flash("You were logged out.")
    return redirect(url_for('index'))


def login_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if not g.is_authenticated:
            return redirect(url_for('auth.login'))

        return view(**kwargs)

    return wrapped_view
