from flask import Flask, render_template, request, redirect, url_for, session
from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.security import check_password_hash
import os
import bcrypt
from functools import wraps
import pickle
import mariadb

app = Flask(__name__, static_url_path='/ecfs/static')

# In production, figure out a better way to manage secrets
cred_path='/home/ooodot10/ECFS_fb/creds.pkl'
creds=pickle.load(open(cred_path, 'rb'))
app.secret_key = creds['APP_PY_SECRET_KEY']

conn = mariadb.connect(
    user=creds['DATABASE_USER'],
    password=creds['DATABASE_PASS'],
    host=creds['DATABASE_HOST'],
    port=creds['DATABASE_PORT'],
    database=creds['DATABASE_NAME']
)

curs=conn.cursor()

# Configure app to work behind a proxy
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1)

# Configure session to work behind proxy
app.config['SESSION_COOKIE_PATH'] = '/ecfs/'
app.config['SESSION_COOKIE_SECURE'] = True  # Set to True to allow only HTTPS-only cookies
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'logged_in' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/ecfs/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        # Note this is the appropriate way to do the query to avoid SQL injection
        # also note that the comma after ['username'] is necessary to make it a tuple, even if it has only one element, 
        # which is what function is expecting
        curs.execute("SELECT * FROM Users WHERE username=%s", (request.form['username'],))
        result=curs.fetchone()
        invalid=True
        if not result is None:
            (id, user, pw, email, locked)=result
            # if check_password_hash(pw, request.form['password']):
            if bcrypt.checkpw(request.form['password'].encode('utf-8'), pw.encode('utf-8')):
                session['logged_in'] = True
                invalid=False
                return redirect(url_for('hello'))
        if invalid:
            return render_template('Error.html')
    return render_template('login.html')

@app.route('/ecfs/')
@login_required
def index():
    return redirect(url_for('hello'))

@app.route('/ecfs/hello', methods=['GET', 'POST'])
@login_required
def hello():
    if request.method == 'POST':
        if request.form['Pizza']=='Hawaii':
            contact_info = {
                'name': 'John Doe',
                'email': 'john@example.com',
                'phone': '555-1234',
                'image': '180.jpg'
            }
            
            return render_template('Card.html', contact=contact_info)
        else:
            return render_template('Error.html')
    return render_template('hello.html')


@app.route('/ecfs/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=9000, debug=False)