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

auth = Blueprint('auth', __name__)

# GET METHODS
@auth.route('/login')
def login():
    return render_template("no-logged/login.html")


@auth.route('/signup')
def signup():
    return render_template("no-logged/signup.html")

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


# POST METHODS
@auth.route('/signup' , methods=["POST"])
def signup_post():
    # Validación de usuario va por acá
    email = request.form.get('email')
    name = request.form.get('name')
    password = request.form.get('password')
    if email == "":
        flash("emailBad")
        return redirect(url_for('auth.signup'))
    user = User.query.filter_by(email=email).first() # Si se encontró un usuario, el email ya está registrado

    if user:
        flash("emailExists")
        return redirect(url_for('auth.signup'))

    # Creo un nuevo usuario con la información del formulario. Hasheo toda la información para no guardarlo como formato texto
    new_user = User(email=email, name=name, password=generate_password_hash(password, method="sha256"))

    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')
    remember = True if request.form.get('remember') else False
    user = User.query.filter_by(email=email).first()
    
    # Si no encontró un usuario o la contraseña no coincide...
    if not user or not check_password_hash(user.password, password):
        flash("badCredentials")
        return redirect(url_for('auth.login'))
    # Sino, logeo el usuario
    login_user(user, remember=remember)
    return redirect(url_for('main.dashboard'))


