from flask import Flask, render_template, request, redirect, send_from_directory
from config import app, db, bcrypt
from models import Contact, User
from werkzeug.utils import secure_filename
from werkzeug.exceptions import RequestEntityTooLarge
import os


@app.route('/')
def index():
    files = os.listdir(app.config['UPLOAD_DIRECTORY'])
    images = []
    
    for file in files:
        if os.path.splitext(file)[1].lower() in app.config['ALLOWED_EXTENSIONS']:
            images.append(file)
    return render_template('index.html', images=images)

@app.route('/upload', methods=["POST"])
def upload():
    try:
        file = request.files['file']
        file_extension = os.path.splitext(file.filename)[1] # [0] is the filename
        
        # save the file if it exists
        if file:
            if file_extension not in app.config['ALLOWED_EXTENSIONS']:
                return 'File is not an image'
            file.save(os.path.join(
                app.config['UPLOAD_DIRECTORY'],
                secure_filename(file.filename)
            ))
    except RequestEntityTooLarge: # except Exception would catch all errors instead of specified
        return 'File is larger than the limit of 16mb.'
    
    return redirect('/')

@app.route("/mail", methods=["POST"])
def mail():
    email = request.json["email"]
    password = request.json["password"]
    order = request.json["order"]
    
    
    if email is None:
        return jsonify({"error": "Unauthorized"}), 401
    
    if not bcrypt.check_password_hash(user.password, password):
        return jsonify({"error": "Unauthorized"}), 401
    
    # Cache session with redis
    session["user_id"] = user.id
    
    return jsonify({
        "id": user.id,
        "email": user.email
    })
        
@app.route("/orders", methods=["GET"])
def orders():
    


# Handle Images
@app.route('/serve-image/<filename>', methods=['GET'])
def serve_image(filename):
  return send_from_directory(app.config['UPLOAD_DIRECTORY'], filename)


# Main
if __name__ == "__main__":
    # Initialize database connection
    with app.app_context():
        db.create_all()
        
    app.run(debug=True, port=5080)