from flask import Blueprint, render_template, request, url_for, flash, redirect
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, logout_user, login_required, current_user
from .models import User
from . import db
from werkzeug.exceptions import abort


auth = Blueprint('auth', __name__)


@auth.route('/login')
def login():
    return render_template('login.html')


@auth.route('/signup')
def signup():
    return render_template('signup.html')


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('main.index'))


@auth.route('/signup', methods=['POST'])
def signup_post():
    email = request.form.get('email')
    name = request.form.get('name')
    password = request.form.get('password')
    roles = request.form.get('roles')

    user = User.query.filter_by(email=email).first()

    if user:
        flash('Email address already exists')
        return redirect(url_for('auth.signup'))

    superuser = User.query.filter_by(id=1).first()
    if not superuser:
        roles = 'superuser'

    # create a new user with the form data. Hash the password so the plaintext version isn't saved.
    new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256'),
                    roles=roles)

    # add the new user to the database
    db.session.add(new_user)
    db.session.commit()
    return redirect(url_for('auth.login'))


@auth.route('/login', methods=['POST'])
def login_post():
    email = request.form.get('email')
    password = request.form.get('password')
    access_rights = request.form.get('access_rights')
    remember = True if request.form.get('remember') else False

    user = User.query.filter_by(email=email).first()

    if not user or not check_password_hash(user.password, password):
        flash('Please check your login details and try again.')
        return redirect(url_for('auth.login'))

    login_user(user, remember=remember)
    return redirect(url_for('main.profile'))


@auth.route('/all_users')
@login_required
def all_users():
    if current_user.roles == 'superuser':
        users = db.session.query(User).all()
        return render_template('users.html', users=users)
    else:
        return redirect(url_for('main.profile'))


def get_user(user_id):
    user = db.session.query(User).get(user_id)
    if user is None:
        abort(404)
    return user


@auth.route('/<int:user_id>')
@login_required
def one_user(user_id):
    user = get_user(user_id)
    return render_template('user.html', user=user)


@auth.route('/create', methods=('GET', 'POST'))
@login_required
def create():
    if current_user.roles == 'superuser':
        if request.method == 'POST':
            email = request.form['email']
            name = request.form['name']
            password = request.form['password']
            roles = request.form['roles']

            if not name:
                flash('Name is required!')
            else:
                new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256'),
                                roles=roles)
                db.session.add(new_user)
                db.session.commit()
                return redirect(url_for('main.profile'))

        return render_template('create.html')
    else:
        return redirect(url_for('main.profile'))


@auth.route('/<int:user_id>/edit', methods=('GET', 'POST'))
@login_required
def edit(user_id):
    user = get_user(user_id)

    if request.method == 'POST':
        roles = request.form['roles']

        if not roles:
            flash('Поле РОЛЬ обязательно')
        else:
            user.roles = roles
            db.session.commit()
            return render_template('user.html', user=user)

    return render_template('edit.html', user=user)


@auth.route('/<int:user_id>/delete', methods=('POST',))
@login_required
def delete(user_id):
    user = get_user(user_id)
    db.session.delete(user)
    flash('User deleted!')
    return redirect(url_for('main.profile'))
