from flask import Flask, render_template, redirect, request, session, flash
from mysqlconnection import connectToMySQL
from flask_bcrypt import Bcrypt        
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')

app = Flask(__name__)
bcrypt = Bcrypt(app) 
app.secret_key = 'keep it secret, keep it safe'

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/create_user', methods=['POST'])
def create_user():
    if len(request.form['first_name']) < 1:
        flash(u'Please enter first name', 'First Name error:')
    if len(request.form['last_name']) < 1:
        flash(u'Please enter last name', 'Last Name error:')
    if not EMAIL_REGEX.match(request.form['email']):
        flash("Invalid email address!")
    if len(request.form['password']) < 8:
        flash("Password should be at least 8 characters")
    if request.form['confirm_password'] != request.form['password']:
        flash("Passwords Don't match!")
    if not '_flashes' in session.keys():
        flash("Friend successfully added!")
        pw_hash = bcrypt.generate_password_hash(request.form['password'])
        print(pw_hash)
        query = "INSERT INTO users (first_name,last_name,email,password,created_at,updated_at) VALUES (%(first_name)s,%(last_name)s,%(email)s,%(password)s,NOW(),NOW())"
        data = {
            "first_name":request.form['first_name'],
            "last_name": request.form['last_name'],
            "email": request.form['email'],
            "password": pw_hash
        }
        mysql = connectToMySQL('users')
        result = mysql.query_db(query,data)
        print(result)
        session['id'] = result
        return redirect('/success')
    else:
        return redirect('/')


@app.route('/login_user', methods=['POST'])
def login_user():
    query = "SELECT * FROM users WHERE email = %(email)s;"
    data = {
        "email": request.form['email'],
    }
    mysql = connectToMySQL('users')
    result = mysql.query_db(query,data)
    print("#########",result)
    if len(result) > 0:
        if bcrypt.check_password_hash(result[0]['password'], request.form['password']):
            flash("Logged in successfully added!") 
            session['id'] = result[0]['id']
            return redirect('/success')
    return redirect("/")

@app.route('/success')
def success():
    if 'id' not in session:
        return redirect("/")
    query = "SELECT * FROM users WHERE id = %(id)s;"
    data = {
        "id": session['id'],
    }
    mysql = connectToMySQL('users')
    result = mysql.query_db(query,data)
    print("$$$$$$$",result)
    session['name'] = f"{result[0]['first_name']} {result[0]['last_name']}"
    return render_template("success.html")

@app.route('/logout')
def logout():
    session.clear()
    return redirect("/")

if __name__=='__main__':
    app.run(debug=True)